Friddy Joe
Friddy Joe

Reputation: 157

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'] = {}
switches['s1']['port1'] = [0, 0, 0]
switches['s1']['port1'] = [1, 1, 1]
switches['s1']['port2'] = [2, 2, 2]

However, [1, 1, 1] overwrites [0, 0, 0]!

How can I have the value [[0, 0, 0], [1, 1, 1]] for the key 'port1'?

Upvotes: 2

Views: 6842

Answers (2)

timgeb
timgeb

Reputation: 78780

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

Upvotes: 5

Nicolas Heimann
Nicolas Heimann

Reputation: 2581

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]

Upvotes: 2

Related Questions