Source From Here
Question
I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged (i.e. taking the union). The update() method would be what I need, if it returned its result instead of modifying a dictionary in-place:
How can I get that final merged dictionary in z, not x?
HowTo
For dictionaries x and y, z becomes a shallowly merged dictionary with values from y replacing those from x.
In Python 3.9.0 or greater (released 17 October 2020):
PEP-584, discussed here, was implemented and provides the simplest method:
In Python 3.5 or greater:
In Python 2, (or 3.4 or lower) write a function:
I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged (i.e. taking the union). The update() method would be what I need, if it returned its result instead of modifying a dictionary in-place:
- >>> x = {'a': 1, 'b': 2}
- >>> y = {'b': 10, 'c': 11}
- >>> z = x.update(y)
- >>> print(z)
- None
- >>> x
- {'a': 1, 'b': 10, 'c': 11}
HowTo
For dictionaries x and y, z becomes a shallowly merged dictionary with values from y replacing those from x.
In Python 3.9.0 or greater (released 17 October 2020):
PEP-584, discussed here, was implemented and provides the simplest method:
- >>> x = {'a': 1, 'b': 2}
- >>> y = {'b:': 10, 'c': 11}
- >>> z = x | y
- >>> z
- {'a': 1, 'b': 2, 'b:': 10, 'c': 11}
- >>> x = {'a': 1, 'b': 2}
- >>> y = {'b:': 10, 'c': 11}
- >>> z = {**x, **y}
- >>> z
- {'a': 1, 'b': 2, 'b:': 10, 'c': 11}
- def merge_two_dicts(x, y):
- z = x.copy() # start with x's keys and values
- z.update(y) # modifies z with y's keys and values & returns None
- return z
- x = {'a': 1, 'b': 2}
- y = {'b:': 10, 'c': 11}
- z = merge_two_dicts(x, y)
沒有留言:
張貼留言