python列表添加字典_在python中添加数据到字典

1586010002-jmsa.png

Here is my dictionary:

inventory = {

'gold' : 500,

'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key

'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']

}

I need to add 50 to the index of gold.

What should I do? I tried:

inventory['gold'].append(50)

解决方案

gold is not a list. It is an integer, so you use addition:

inventory['gold'] += 50

This uses augmented assignment, which for integers is equivalent to:

inventory['gold'] = inventory['gold'] + 50

If you need gold to be a list as well, and want to end up with [500, 50] as the value, you'll have to replace the current value with a list:

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

If you need to add multiple values over time, and don't know if gold is a list or a simple integer, and cannot change the original dictionary to always use a list, you could use exception handling:

try:

inventory['gold'].append(50)

except AttributeError:

# not a list yet

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

It would be far easier to maintain your project if you started with gold always being a list object, however.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值