Home > Mobile >  Append a nested dictionary to a dictionary in python
Append a nested dictionary to a dictionary in python

Time:11-20

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

CodePudding user response:

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]}
  • Related