gpt4 book ai didi

python - 使用 json 文件中的特定键值对更新 python 字典

转载 作者:行者123 更新时间:2023-12-04 07:12:48 31 4
gpt4 key购买 nike

基本上,我想从 json 文件中获取特定的键和值,并将其附加到 python 中的字典中。到目前为止,我已经想出了如何将所有 json 数据附加到我的字典中,但这不是我想要的。
这是我的 json 文件,其中包含供用户添加到其库存中的项目,其中包含在检查时将显示的文本。

{
"egg" : "This smells funny.",
"stick" : "Good for poking!",
"frying pan" : "Time to cook."
}
我想要完成的是当用户拿起某个项目时,它会从 json 文件导入到作为他们库存的 python 字典中。
import json

inventory = {}


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

x = 'egg'

addInventory(x)

print(inventory)
因此,当用户拿起一个“鸡蛋”时,我想以某种方式从 json 文件中获取该键和值集,并将其附加到我在 python 中的库存字典中。我假设 for 循环可以解决这个问题,但我似乎无法弄清楚。

最佳答案

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)

关于python - 使用 json 文件中的特定键值对更新 python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68969815/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com