简体   繁体   English

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

[英]Adding more values on existing python dictionary key

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?? 有人可以帮忙吗?

>>> 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 dict as a variable name - it shadows built-in dict type. 另外,不要使用dict作为变量名 - 它会影响内置的dict类型。 See what can possibly happen: 看看会发生什么:

>>> 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

做这个:

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

尝试这个:

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

Instead of assigning {'dist':12} to dict['a'] , use the update method. 不要将{'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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM