Example of how to merge two dictionaries in Python share

Source: Internet
Author: User
The dictionary is the only type of mapping in the Python language, which is often encountered in our daily work, the following article mainly introduces you about how to gracefully merge two dictionaries (dict) in Python, the text of the sample code introduced in very detailed, the need for friends can refer to the reference, Let's take a look below.

Objective

The dictionary is one of the most powerful data types in Python, this article will give you a detailed introduction about the Python merge two dictionaries (DICT) related content, share out for everyone to refer to the study, words not to say, come together to see the detailed introduction bar.

One line of code merges two Dict

Suppose there are two dict x and Y, combined into a new dict that do not change the values of x and Y, for example


x = {' A ': 1, ' B ': 2} y = {' B ': 3, ' C ': 4}

Expect to get a new result Z, if key is the same, then y overrides X. The desired result is


>>> z{' A ': 1, ' B ': 3, ' C ': 4}

In PEP448, there is a new syntax that can be implemented, and the syntax is supported in python3.5, and the merge code is as follows


z = {**x, **y}

A line of code that is duly completed. Since many people are still using python2, there is a more elegant way for python2 and python3.0-python3.4, but two lines of code are required.


z = x.copy () z.update (y)

The above method, Y will overwrite the contents of x, so the final result is b=3.

How to do a line without using python3.5

If you are not using Python 3.5, or you need to write backward-compatible code, and you want to run in a single expression, the most efficient way is to put it in a function:


def merge_two_dicts (x, y): "" "Given-dicts, merge them into a new dict as a shallow copy." "" Z = X.copy () z.update (y) r Eturn Z

Then a line of code completes the call:


z = merge_two_dicts (x, y)

You can also define a function that merges multiple dict, such as


def merge_dicts (*dict_args): "" "Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. "" "result = {} for dictionary in Dict_args:result.update (dictionary) return result

You can then use this


z = merge_dicts (A, B, C, D, E, F, g)

All of these, the same key, are covered in front of the back.

Some of the less elegant demonstrations

Items

Some people will use this method:


z = dict (x.items () + y.items ())

This is essentially creating two lists in memory, creating a third list, creating a new dict after the copy is complete, and deleting the first three lists. This method consumes performance, and for Python3, this cannot be executed successfully because items () return is an object.


>>> C = dict (A.items () + b.items ()) Traceback (most recent call last): File "<stdin>", line 1, in <module >typeerror:unsupported operand type (s) for +: ' Dict_items ' and ' Dict_items '

You have to explicitly cast it into list, which z = dict(list(x.items()) + list(y.items())) is too wasteful of performance. Also, the method that you want to do with the returned list will fail for Python3, and the method of the Union, which causes the duplicate key to be indeterminate at the value, is items() completely inappropriate if you have a priority requirement for the two dict.


>>> x = {' A ': []}>>> y = {' B ': []}>>> dict (X.items () | Y.items ()) Traceback (most recent call LA ST): File "<stdin>", line 1, in <module>typeerror:unhashable type: ' List '

Here is an example where y should have precedence, but because of any set order, the value of x is preserved:


>>> x = {' A ': 2}>>> y = {' A ': 1}>>> dict (X.items () | Y.items ()) {' A ': 2}

constructor function

Someone else would use it.


z = dict (x, **y)

This is good, more efficient than the previous two-step approach, but the readability is poor, not enough pythonic, if the key is not a string, Python3 still fail to run


>>> C = Dict (A, **b) Traceback (most recent call last): File "<stdin>", line 1, in <module>typeerror: Keyword arguments must be strings

Guido van Rossum said: The declaration dict({}, {1:3}) is illegal, because after all it is an abuse mechanism. Although this method is more hacker, but too opportunistic.

Some poor performance, but more elegant methods

The following methods, though poorly performing, are much better than the items method. and supports the priority level.


{k:v for D in dicts for K, V in D.items ()}

You can do this in python2.6.


Dict ((k, V) for D in Dicts for K, V in D.items ())

Itertools.chain will link the iterator on the key-value pair in the correct order:


Import Itertoolsz = Dict (Itertools.chain (X.iteritems (), Y.iteritems ()))

Performance testing

The following is done on Ubuntu 14.04, in Python 2.7 (System Python):


>>> min (Timeit.repeat (lambda:merge_two_dicts (x, y)) 0.5726828575134277>>> min (Timeit.repeat ( Lambda: {k:v for D in (x, y) for K, V in D.items ()})) 1.163769006729126>>> min (Timeit.repeat (lambda:dict (Iterto Ols.chain (X.iteritems (), Y.iteritems ()))) 1.1614501476287842>>> min (Timeit.repeat (lambda:dict (k, v) for D In (x, y) for K, V in D.items ())) 2.2345519065856934

In the python3.5


>>> min (timeit.repeat (lambda: {**x, **y})) 0.4094954460160807>>> min (Timeit.repeat (lambda:merge_ Two_dicts (x, y))) 0.7881555100320838>>> min (timeit.repeat (lambda: {k:v for D "(x, y) for K, V in D.items ()})) 1 .4525277839857154>>> min (timeit.repeat (lambda:dict (Itertools.chain (X.items (), Y.items ()))) 2.3143140770262107>>> min (Timeit.repeat (lambda:dict (k, v) for D in (x, y) for K, V in D.items ())) 3.20691127999 45287

Summarize

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.