Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Append a nested dictionary to a dictionary in python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Instead of

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

>Solution :

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]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading