在python中添加数据到字典 [英] Add data to dictionary in python

查看:2726
本文介绍了在python中添加数据到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的字典:

  inventory = {
'gold':500,
' pouch':['flint','twine','gemstone'],#分配一个新的列表pouch键
'背包':['xylophone','dagger','bedroll','bread loaf']
}

我需要添加50到$ code>金。
我该怎么办?我试过:

 库存['gold']。append(50)
/ pre>

解决方案

gold 不是列表。这是一个整数,所以你使用添加

  'gold'] + = 50 

这使用扩充赋值,其中的整数相当于: p>

 库存['gold'] =库存['gold'] + 50 
pre>

如果您需要 gold 作为列表,并希望最终获得 [500,50] 作为价值,您必须使用列表将替换当前值:

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

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

  try:
inventory ['gold']。append(50)
除了AttributeError:
#不是一个列表
库存['g old'] = [inventory ['gold'],50]

这将更容易维护您的项目,如果您开始 gold 始终是列表对象。


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.

这篇关于在python中添加数据到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆