Skip to content Skip to sidebar Skip to footer

Appending To Lists Stored In A Nested Dictionary

If I want to create a dictionary that looks like this: switches = {'s1': {'port1': [[0, 0, 0], [1, 1, 1]], 'port2': [2,2,2]}} I have tried: switches = {} switches['s1'] = {} switc

Solution 1:

Expanding on idjaw's comment and keksnicoh's answer, I think you can make your life a little bit easier by using a 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]]})})

You can use it just like a regular dictionary:

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

Solution 2:

Your dict keys may be some kinda list, so you can append multiple values to it.

switches['s1'] = {}
switches['s1']['port1'] = list()
switches['s1']['port1'].append([0, 0, 0])
switches['s1']['port1'].append([1, 1, 1])

Also if you add single values you may also put them into a list so you can access the dict always by the same way:

switches['s1']['port2'] = list([2,2,2])

Getting the first port would be

print(switches['s1']['portN'][0]

Post a Comment for "Appending To Lists Stored In A Nested Dictionary"