Home  >  Article  >  Backend Development  >  Summary of four dictionary merging methods in Python

Summary of four dictionary merging methods in Python

黄舟
黄舟Original
2017-08-10 14:09:302008browse

Merging dictionaries (dict) in Python is a relatively common problem. The following article mainly summarizes and introduces the four methods of dictionary (dict) merging in Python. Friends who need it can refer to it. Let's learn together with the editor.

This article mainly introduces you to the four methods of merging dictionaries (dict) in Python, and shares them for your reference and study. Without further ado, let’s take a look at the detailed introduction:

Dictionary is the only mapping type in the Python language.

There is a one-to-many relationship between the hash value (key, key) and the pointed object (value, value) in the mapping type object, which is usually considered to be variable. hash table.

The dictionary object is mutable. It is a container type that can store any number of Python objects, which can also include other container types.

The difference between dictionary type and sequence type:

## 1. The methods of storing and accessing data are different.


2. Sequence types only use numeric keys (indexed in numerical order from the beginning of the sequence);


3. Mapping types can use other object types as keys (For example: numbers, strings, tuples, strings are generally used as keys), unlike sequence type keys, mapping type keys are directly or indirectly associated with stored data values.

5. The data in the mapping type is arranged in an unordered manner. This is different from sequence types, which are arranged in numerical order.

6. Mapping types use keys to directly "map" to values.

Dictionaries are one of the most powerful data types in Python.

In reality, we often encounter dictionary merging operations. How to implement it? The following is a summary


[Method 1] Use dict(d1 .items() + d2.items()) method

##Remarks:

1. d1.items()
Get the list of key-value pairs of the dictionary

2. d1.items() + d2.items()
Make one New list

3. dict(d1.items()+d2.items())
Convert the merged list into a new dictionary

[Method 2] Use the dictionary’s update() method

##[Method 3] Use the dictionary’s dict(d1, * *d2) Method

[Method 4] Conventional processing method with the help of dictionary

Summarize

The above is the detailed content of Summary of four dictionary merging methods in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn