Mordork
Mordork

Reputation: 49

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.

Upvotes: 2

Views: 1088

Answers (3)

Bhagyesh Dudhediya
Bhagyesh Dudhediya

Reputation: 1864

The reason for your code not working is you are just doing inventory.update(f), so it's as good as creating a copy of f as inventory. If you want your inventory to just contain a key:value of specific key, then below code will work:

import json

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

addInventory(x)

print(inventory)

Upvotes: 0

TSnake
TSnake

Reputation: 480

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)

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71620

Try this:

import json

inventory = {}


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

addInventory(x)

print(inventory)

Upvotes: 0

Related Questions