python3 快速合并字典

当有两个字典需要合并时,考虑到字典的特殊性,你需要先将其转成列表的形式,相加运算后再转回字典,如下:

x = {'a':1, 'b':3}
y = {'c': 5, 'd': 8}
z = dict(list(x.items()) + list(y.items()))
print(z)
# {'d': 8, 'c': 5, 'a': 1, 'b': 3}

 python3.5中提供了更加方便的方法:

x = {'a':1, 'b':3}
y = {'c': 5, 'd': 8}
#z = dict(list(x.items()) + list(y.items()))
z = {**x, **y}
print(z)

 结果与上面的一样,而且速度更快(不知道原理,只是看资料说更快),这方法很python 有木有?

原文地址:https://www.cnblogs.com/Andy963/p/7041231.html