Python deletes the keys of a dictionary and merges two dictionaries

As the basic data type of python, the operation of the dictionary is still indispensable in the work. Here is how to delete the key and merge the two dictionaries on the dictionary.

The two dictionaries are as follows:

  1. >>> d1 = {'name' : 'revotu', 'age' : 99}

  2. >>> d2 = {'age' : 24, 'sex' : 'male'} 

Deleting is relatively simple, just del d2['age'], so I won’t explain too much here.

Mainly talk about how to merge two dictionaries:

The result of the merge is as follows (that is, when the keys are the same, the following dictionary values ​​overwrite the previous dictionary):

  1. >>> d

  2. {'sex': 'male', 'name': 'revotu', 'age': 24}

First of all, explain that the dictionary does not support the + addition operation

  1. >>> d1 + d2

  2. Traceback (most recent call last):

  3. File "<stdin>", line 1, in <module>

  4. TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

Now summarize the following methods and a brief analysis and comparison.

  1. Update multiple times
    Here is the simplest way to merge dictionaries:
  2. >>> d = {}

  3. >>> d.update(d1)

  4. >>> d.update(d2) 

First create an empty dictionary, and use the update method to add elements to the dictionary. Note that d1 is added first to ensure that the repeated keys of d2 added later will cover d1.
This method meets our requirements and is clear and clear, but three lines of code always feel Pythonic enough.

  1. Copy first, then update
    First copy the d1 dictionary to create a new dictionary, and then use d2 to update the new dictionary created earlier.
  2. >>> d = d1.copy()

  3. >>> d.update(d2) 

Compared with method 1, this method of copying d1 more clearly shows d1 as the default value.

  1. The dictionary constructor can
    also use the dictionary constructor dict() to copy the dictionary and then update it:
  2. >>> d = dict(d1)

  3. >>> d.update(d2) 

It is similar to method two, but there is no method two that is straightforward.

  1. Keyword parameter hackYou
    may have seen this clever solution:
  2. >>> d = dict(d1 , **d2) 

There is only one line of code, which looks cool, but there is a problem. This hack technique only works when the keys of the dictionary are strings.

It looks cool, but it is not universal. The key of the dictionary must be a string to use this keyword parameter method.

  1. Dictionary comprehension
    can be used to solve this problem:
  2. >>> d = {k:v for d in [d1, d2] for k,v in d.items()} 

The dictionary comprehension method meets the requirements, but the nested dictionary comprehension is not so clear and not easy to understand.

  1. Element splicing
    We get a list of elements from each dictionary, splice the lists, and then use the spliced ​​lists to construct the dictionary:
  2. >>> d = dict(list(d1.items()) + list(d2.items())) 

Moreover, the element of d2 is behind the list, so d1 can be overwritten when the key is repeated. If in Python2, the items() method itself returns a list, there is no need to use list() to convert it into a list.

Element splicing can meet the requirements in constructing a dictionary, but it seems that the code is a bit repetitive.

  1. Element union
    In Python3, the dictionary returns the view object, and the key view object is a collection-like object. If the value in the dictionary can be guaranteed to be uniquely hashable, the view object returned by items is also similar. Objects of the collection:
    >>> d = dict(d1.items() | d2.items())

This method is very interesting, but not accurate, because the collection is unordered, there is no guarantee who will cover who when the key is repeated, and the values ​​in the dictionary are usually not hashable, of course, it cannot return a collection-like object.

  1. Chain items
    So far, among the solutions we have discussed, the one that is most in line with Python language habits and implemented with only one line of code is to create a list of two items and then stitch them into a dictionary.
    We can use itertools.chain to simplify the item splicing process:
    >>> d = dict(chain(d1.items(), d2.items()))

This scheme is very good, and may be more efficient than creating two unnecessary lists.

  1. ChainMap
    collections. ChainMap can combine multiple dictionaries or mappings and logically merge them into a single mapping structure
  2. >>> d = dict(ChainMap(d1, d2))

This method is also very pythonic, and it is also a universal method.

  1. Dictionary splitting
    In Python 3.5+, a new way of merging dictionaries can be used:
    >>> d = {**d1, **d2}

This line of code is very pythonic. If your python version is 3.5+, this method is a good choice.

to sum up

The above mentioned ten ways to merge two dictionaries into a new dictionary. Which one you use depends on you.
If you are using Python3.5+, then the new syntax of dictionary splitting should be suitable for you:

    1. >>> d = {**d1, **d2}

Guess you like

Origin blog.csdn.net/weixin_42575020/article/details/107565061