Hacker News new | ask | show | jobs
by JupiterMoon 3201 days ago
What happens to duplicate keys?
3 comments

They get overwritten by the value of the dictionary that came last.

  >>> dict1 = {"key1": 1, "key2": "hello", "key3": [1, 2, 3]}
  >>> dict2 = {key1": 1, "key2": "world", "key3": [1, 4], "key4": "4"}

  >>> {**dict1, **dict2}
  {'key1': 1, 'key2': 'world', 'key3': [1, 4], 'key4': '4'}
Lots of code to show that. How 'bout this: ;-)

  >>> {**{'a': 'first'}, **{'a': 'second'}}
  {'a': 'second'}
I think it raises an exception.

https://www.python.org/dev/peps/pep-0448/

EDIT: yeah, nvm, it's what everyone else said.

No it doesn't, you simply get the value from the last dict:

  >>> a = {'x': 1}
  >>> b = {'x': 2}
  >>> {**a, **b}
  {'x': 2}
  >>> {**b, **a}
  {'x': 1}
Last pair wins, same as setting an existing key or doing an update() with an existing key.