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

update dictionaries in the list comprehension

There is a dictionary:

d = [{"a":1, "b":2},{"a":3, "b":4},{"a":5, "b":6}]

I’d like to update values of keys b.

d = [{**m}.update({"b":5}) for m in d]

but I don’t understand why this gives
d = [None, None, None]

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

I’d expect
d = [{"a":1, "b":5},{"a":3, "b":5},{"a":5, "b":5}]

>Solution :

dict.update returns None and updates the dict in-place. You can try using the | operator which returns a new dict:

d = [m | {"b":5} for m in d]
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