Append a nested dictionary to a dictionary in python

Question:

I’m trying to append a nested dictionary to a dictionary, I have searched the internet and couldn’t find an answer.

I tried

Colors = {}

a = {"1:1":{255,1,2}}
b = {"2:1":{1,255,2}}
Colors.update(a)
Colors.update(b)

print(Colors)

It prints

{'1:1': {1, 2, 255}, '2:1': {1, 2, 255}}

Instead of

{'1:1': {255,1,2}, '2:1': {1,255,2}}

Asked By: Richard

||

Answers:

The reason the values don’t keep their order is because you’re using sets and not lists. Unlike lists, sets are unordered (you can read more here).
To fix your issue, you can use lists instead (note the {} turned into []:

Colors = {}

a = {"1:1":[255,1,2]}
b = {"2:1":[1,255,2]}
Colors.update(a)
Colors.update(b)

print(Colors)

Which prints:

{'1:1': [255, 1, 2], '2:1': [1, 255, 2]}
Answered By: Adid
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.