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

Pan*_*chi 15 python dictionary

我是python的新手,我在制作字典时遇到困难..请帮助:)

这是我开始的:

dict = {}
dict['a']={'ra':7, 'dec':8}
dict['b']={'ra':3, 'dec':5}
Run Code Online (Sandbox Code Playgroud)

到目前为止一切都很完美.我明白了:

In [93]: dict
Out[93]: {'a': {'dec':8 , 'ra': 7}, 'b': {'dec': 5, 'ra': 3}}
Run Code Online (Sandbox Code Playgroud)

但现在,如果我想为关键'a'添加更多内容,我会:

dict['a']={'dist':12}
Run Code Online (Sandbox Code Playgroud)

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

In [93]: dict
Out[93]: {'a': {'dist':12}, 'b': {'dec': 5, 'ra': 3}}
Run Code Online (Sandbox Code Playgroud)

我想拥有的是:

In [93]: dict
Out[93]: {'a': {'dec':8 , 'ra': 7, 'dist':12}, 'b': {'dec': 5, 'ra': 3}}
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

ale*_*cxe 20

>>> 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}}
Run Code Online (Sandbox Code Playgroud)

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

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

>>> 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}}
Run Code Online (Sandbox Code Playgroud)

另外,不要将其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
Run Code Online (Sandbox Code Playgroud)