Search code examples
pythonlist-comprehension

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]

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]