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

modifying a dictionary with a list item elements

I want to add to the first key of a dict the first element of a list, same for the second and so on. How can I do that?

d = {'a_': 1, 'b_': 2}
l = ['orange', 'apple']

I would like to get:

d = {'a_orange': 1, 'b_apple': 2}

I tried: A = [{f'{k}{items}': v for k, v in d.items() for j in l}

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

but this produce: ['a_orange', 'a_apple', 'a_orange', 'a_apple'] which is not what I am looking for.

>Solution :

Try dict comprehension with zip but this assumes that d and l are the same length and there is only one value for each key in d

d = {'a_': 1, 'b_': 2}
l = ['orange', 'apple']

{d[0]+l:d[1] for d,l in zip(d.items(),l)} # -> {'a_orange': 1, 'b_apple': 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