pythonjsonpython-3.xdictionaryadventure

Updating a python dictionary with specific key, value pairs from a json file


Basically, I want to get a specific key and value from a json file and append it to a dictionary in python. So far, I've figured out how to append all the json data into my dictionary, but that's not what I want.

This is my json file with items for a user to add to their inventory with text that will show when being examined.

{
    "egg"        : "This smells funny.",
    "stick"      : "Good for poking!",
    "frying pan" : "Time to cook."
}

What I'm trying to accomplish is for when a user picks up a certain item it gets imported from the json file into a python dictionary which acts as their inventory.

import json

inventory = {}


def addInventory(args):
    f = open('examine.json', 'r')
    dic = json.load(f)
    inventory.update(dic)
    
x = 'egg'

addInventory(x)

print(inventory)

So when the user picks up an 'egg' I want to somehow get that key and value set from the json file and append it to my inventory dictionary in python. I'm assuming a for loop would work for this, but I cannot seem to figure it out.


Solution

  • import json
    
    
    
    with open('examine.json', 'r') as f:
        json_inventory = json.load(f)
    
    def addInventory(x):
        try:
           my_inventory[x] = json_inventory[x]
        except Exception as e:
           logging.info("User trying to add something that is not in the json")
          
    def removeInventory(x):
       try:
           my_inventory.pop(x)
       except Exception as e:
           logging.info("User trying to remove something that is not in the inventory")
    
    
    my_inventory = {}
    x = 'egg' 
    addInventory(x) #add to your inventory
    print(my_inventory)
    x = 'stick'
    addInventory(x) #add to your inventory again 
    print(my_inventory)
    x = 'egg'
    removeInventory(x) #remove from your inventory
    print(my_inventory)