在现有的 python 字典键上添加更多值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18851325/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:03:27  来源:igfitidea点击:

Adding more values on existing python dictionary key

pythondictionary

提问by Panchi

I am new to python and i am stuck while making a dictionary.. please help :)

我是 python 的新手,我在制作字典时被卡住了..请帮忙:)

This is what I am starting with :

这就是我的开始:

dict = {}
dict['a']={'ra':7, 'dec':8}
dict['b']={'ra':3, 'dec':5}

Everything perfect till now. I get :

到目前为止一切都很完美。我得到:

In [93]: dict
Out[93]: {'a': {'dec':8 , 'ra': 7}, 'b': {'dec': 5, 'ra': 3}}

But now, if I want to add more things to key 'a' and i do :

但是现在,如果我想向键 'a' 添加更多内容,我会这样做:

dict['a']={'dist':12}

Then it erases the previous information of 'a' and what i get now is :

然后它删除了'a'的先前信息,我现在得到的是:

In [93]: dict
Out[93]: {'a': {'dist':12}, 'b': {'dec': 5, 'ra': 3}}

What i get want to have is :

我想要的是:

In [93]: dict
Out[93]: {'a': {'dec':8 , 'ra': 7, 'dist':12}, 'b': {'dec': 5, 'ra': 3}}

Can someone please help??

有人可以帮忙吗??

采纳答案by alecxe

>>> d = {}
>>> d['a'] = {'ra':7, 'dec':8}
>>> d['b'] = {'ra':3, 'dec':5}
>>> d['a']['dist'] = 12
>>> d
{'a': {'dec': 8, 'dist': 12, 'ra': 7}, 'b': {'dec': 5, 'ra': 3}}

If you want to update dictionary from another dictionary, use update():

如果要从另一个字典更新字典,请使用update()

Update the dictionary with the key/value pairs from other, overwriting existing keys.

使用其他键/值对更新字典,覆盖现有键。

>>> d = {}
>>> d['a'] = {'ra':7, 'dec':8}
>>> d['b'] = {'ra':3, 'dec':5}
>>> d['a'].update({'dist': 12})
>>> d
{'a': {'dec': 8, 'dist': 12, 'ra': 7}, 'b': {'dec': 5, 'ra': 3}}

Also, don't use dictas a variable name - it shadows built-in dicttype. See what can possibly happen:

另外,不要dict用作变量名 - 它会影响内置dict类型。看看可能会发生什么:

>>> dict(one=1)
{'one': 1}
>>> dict = {}
>>> dict(one=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable

回答by Panchi

Do this:

做这个:

dict['a']['dist'] = 12

回答by chepner

Instead of assigning {'dist':12}to dict['a'], use the updatemethod.

而不是分配{'dist':12}dict['a'],使用该update方法。

dict['a'].update( {'dist':12} )

This has the advantage of not needing to "break apart" the new dictionary to find which key(s) to insert into the target. Consider:

这具有不需要“分解”新字典来查找要插入到目标中的键的优点。考虑:

a = build_some_dictionary()
for k in a:
    dict['a'] = a[k]

vs.

对比

dict['a'].update(a)

回答by Who8MyLunch

Try this:

尝试这个:

dict['a'].update( {'dist': 12} )

dict['a'].update( {'dist': 12} )