将键和值附加到键值对字典 Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35830335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append Key and Value to a Key Value pair Dictionary Python
提问by NellMartin
My intended goal is to append a key value pair to a value in inside of a dictionary:
我的预期目标是将键值对附加到字典内部的值:
I have the following:
我有以下几点:
crucial = {'C': {'C': 0, 'B': 1}}
done = {}
for each in crucial:
for i in each:
done['D'] = 0
print(done)
print(crucial[i].append(done))
The output is:
输出是:
Traceback (most recent call last):
File "C:\Users\User\Documents\Programming Full-Stack\Python\Exercise Files Quick Start\conditionals.py", line 13, in <module>
print(crucial[i].append(done))
AttributeError: 'dict' object has no attribute 'append'
{'D': 0}
Expected output:
预期输出:
{'C': {'C': 0, 'B': 1, 'D':0}}
Therefore, can anyone provide me a guideline to append a key value pair to that value field in the outer dictionary?
因此,任何人都可以为我提供将键值对附加到外部字典中的该值字段的指南吗?
Different approaches tried: So far I've tried converting the dictionary to a list declaring d as [], not with {}. I also tried putting .extend instead of .append. But in none of those cases I've got the result I wanted.
尝试了不同的方法:到目前为止,我已经尝试将字典转换为一个列表,将 d 声明为 [],而不是使用 {}。我也试过用 .extend 代替 .append。但在这些情况下,我都没有得到我想要的结果。
Thank you in advance
先感谢您
回答by idjaw
As the error states, dict
has no attribute append
. There is no append
method in the dictionary object. To assign a value to a particular key in a dictionary, it is simply:
正如错误所述,dict
没有属性append
。append
字典对象中没有方法。要为字典中的特定键赋值,只需:
d[key] = new_value
where new_value can be, if you wish: {'a':1}
如果您愿意, new_value 可以在哪里: {'a':1}
If you are looking to update your dictionary with new data, you can use the update method.
如果您想用新数据更新您的字典,您可以使用 update 方法。
d.update(new_stuff)
In your code, simply change your append, similar to the example I provided. I corrected it here:
在您的代码中,只需更改您的 append,类似于我提供的示例。我在这里更正了:
crucial = {'C': {'C': 0, 'B': 1}}
done = {}
for each in crucial:
for i in each:
done['D'] = 0
print(done)
crucial[i].update(done)
print(crucial)
回答by Henin RK
Python has a update function to add new items to dictionary
Python 有一个更新功能,可以将新项目添加到字典中
crucial .update({'D':'0'})