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

Add element of list in dictionary of other list at the same index

I have a list of values, and a list of dictionaries such as:

my_values = ["A", "B", "C"]
my_dicts = [{...}, {...}, {...}]

I would like to unpack my values into my dictionaries so that the value in position n goes in the nth dictionary, such as:

my_new_dicts = [{"value": "A", ...}, {"value": "B", ...}, {"value": "C", ...}]

My list/dict comprehension attempts so far yield a new list of n*n dictionaries.

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

>Solution :

One way to merge two dicts d1 and d2 is {**d1, **d2}. Instead of **d2, or in addition to **d2, you can also explicitly write the new values you want to add to d1.

And then using a list comprehension for my_new_dicts:

my_new_dicts = [{**d, 'value': v} for d, v in zip(my_dicts, my_values)]
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