python3如何实现合并字典

小编给大家分享一下python3如何实现合并字典,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

合并两个字典

下面的方法将用于合并两个字典。

def merge_two_dicts(a, b):
    c = a.copy()   # make a copy of a 
    c.update(b)    # modify keys and values of a with the ones from b
    return c
 
 
a = { 'x': 1, 'y': 2}
b = { 'y': 3, 'z': 4}
print(merge_two_dicts(a, b))
# {'y': 3, 'x': 1, 'z': 4}

Python 3.5 或更高版本中,我们也可以用以下方式合并字典:

def merge_dictionaries(a, b)
   return {**a, **b}
 
 
a = { 'x': 1, 'y': 2}
b = { 'y': 3, 'z': 4}
print(merge_dictionaries(a, b))
# {'y': 3, 'x': 1, 'z': 4}

将两个列表转化为字典

如下方法将会把两个列表转化为单个字典。

def to_dictionary(keys, values):
    return dict(zip(keys, values))
 
 
keys = ["a", "b", "c"]    
values = [2, 3, 4]
print(to_dictionary(keys, values))
# {'a': 2, 'c': 4, 'b': 3}

看完了这篇文章,相信你对python3如何实现合并字典有了一定的了解,想了解更多相关知识,欢迎关注行业资讯频道,感谢各位的阅读!