在python中向字典添加数据

2024-05-11 19:22:33 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的字典:

inventory = {
    'gold' : 500,
    'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
    'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}

我需要给gold的索引加50。 我该怎么办?我试过了:

^{pr2}$

Tags: tokeynew字典listflinttwineinventory
3条回答

gold不是一个列表。它是一个整数,因此使用加法

inventory['gold'] += 50

这使用了增广赋值,对于整数,它相当于:

^{pr2}$

如果您还需要gold作为列表,并希望以[500, 50]作为值,则必须使用列表替换当前值:

inventory['gold'] = [inventory['gold'], 50]

如果您需要随时间添加多个值,并且不知道gold是列表还是简单整数,并且无法将原始字典更改为始终使用列表,则可以使用异常处理:

try:
    inventory['gold'].append(50)
except AttributeError:
    # not a list yet
    inventory['gold'] = [inventory['gold'], 50]

但是,如果您以gold始终是一个列表对象来启动,那么维护您的项目会容易得多。在

假设你的意思是你想在黄金上加50英镑。把黄金列为清单:

inventory = {
    'gold' : [500],
    'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
    'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}

inventory['gold'].append(50)

如果你是说加法,那就用Martijn的解决方案。在

如果你想在“白金”键上加60

inventory ["Platinum"] += 60

如果你想保持500的值,同时又有60的值,你需要一些东西来包含它们,比如一个列表。在

你可以用一个列表初始化你的“白金”值,然后在它上面追加500和60。在

^{pr2}$

或者您可以使用defaultdict使其稍微简单一些。在

from collections import defaultdict


inventory = defaultdict (list)  # every missing value is now a list.

inventory ["Platinum"].append (500) # add 500 to the list.
inventory ["Platinum"].append (60) # add 60 to the list.
inventory ["pouch"] = ['Flint', 'twine', 'gemstone'] # create a new key with a new value.
inventory['animals'].extend(['Elephant', 'dog','lion']) # extend list to include.
inventory['pouch'].remove('Flint')

相关问题 更多 >