追加到存储在嵌套字典中的列表

Fri*_*Joe 2 python dictionary

如果我想创建一个如下所示的字典:

switches = {'s1': {'port1': [[0, 0, 0], [1, 1, 1]], 'port2': [2,2,2]}}
Run Code Online (Sandbox Code Playgroud)

我努力了:

switches = {}
switches['s1'] = {}
switches['s1']['port1'] = [0, 0, 0]
switches['s1']['port1'] = [1, 1, 1]
switches['s1']['port2'] = [2, 2, 2]
Run Code Online (Sandbox Code Playgroud)

但是,[1, 1, 1]覆盖[0, 0, 0]

[[0, 0, 0], [1, 1, 1]]我怎样才能获得密钥的值'port1'

tim*_*geb 5

扩展 idjaw 的评论和 keksnicoh 的答案,我认为您可以通过使用defaultdict.

>>> from collections import defaultdict
>>> d = defaultdict(lambda: defaultdict(list))
>>> d['s1']['port1'].append([0, 0, 0])
>>> d['s1']['port1'].append([1, 1, 1])
>>> d['s1']['port2'].append([2, 2, 2])
>>> d
defaultdict(<function <lambda> at 0x7f5d217e2b90>, {'s1': defaultdict(<type 'list'>, {'port2': [[2, 2, 2]], 'port1': [[0, 0, 0], [1, 1, 1]]})})
Run Code Online (Sandbox Code Playgroud)

您可以像普通字典一样使用它:

>>> d['s1']
defaultdict(<type 'list'>, {'port2': [[2, 2, 2]], 'port1': [[0, 0, 0], [1, 1, 1]]})
>>> d['s1']['port1']
[[0, 0, 0], [1, 1, 1]]
Run Code Online (Sandbox Code Playgroud)