2

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.

3 Answers 3

2
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)
Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

This was actually my first way of trying to come up with a solution. It throws up an error: ValueError: dictionary update sequence element #0 has length 1; 2 is required
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.