python2 dict 合并

Release Date: Update date: Total Words: 184 Reading time: 1m by IP: 上海 Share Copy Url

In Python 2, you can merge two dictionaries using the update() method or the dict() constructor with the ** operator.

Here are some examples:

Method 1: Using update()

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

dict1.update(dict2)
print(dict1)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

**Method 2: Using dict() with ****

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

merged_dict = dict(dict1, **dict2)
print(merged_dict)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Method 3: Using dict() with items()

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

merged_dict = dict(list(dict1.items()) + list(dict2.items()))
print(merged_dict)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Note that in Python 2, the update() method modifies the original dictionary, while the other two methods create a new dictionary.

In Python 3.x, you can use the ** operator to merge dictionaries in a more concise way:

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}
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数