python merge
时间: 2023-10-14 17:26:40 浏览: 38
"Merge" in Python typically refers to combining two or more lists or dictionaries into one. There are different ways to merge lists and dictionaries, depending on the desired outcome.
Merging lists:
1. Using the + operator: This is the simplest way to merge two or more lists in Python. It concatenates the lists together.
Example:
```
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(merged_list) # Output: [1, 2, 3, 4, 5, 6]
```
2. Using the extend() method: This method appends all the elements of one list to another list.
Example:
```
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
```
Merging dictionaries:
1. Using the update() method: This method adds the key-value pairs of one dictionary to another dictionary.
Example:
```
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict1.update(dict2)
print(dict1) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
```
2. Using the ** operator: This method merges two dictionaries into one.
Example:
```
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
```
Note: When merging dictionaries, if there are duplicate keys, the values of the last dictionary will overwrite the values of the previous dictionaries.