Skip to content

Latest commit

 

History

History
69 lines (57 loc) · 2.88 KB

Python中使用unpack操作符合并多个字典.org

File metadata and controls

69 lines (57 loc) · 2.88 KB

Python中使用unpack操作符合并多个字典

https://www.techbeamers.com/python-merge-dictionaries/ 看到的,记录一下

当想要创建一个包含多个字典内容的 新字典 对象时,最直观的方法就是调用字典对象的 update 方法了,像这样:

"""
Desc:
  Python program to combine two dictionaries using update()
"""
# Define two existing business units as Python dictionaries
unitFirst = { 'Joshua': 10, 'Ryan':5, 'Sally':20, 'Martha':17, 'Aryan':15}
unitSecond = { 'Versha': 11, 'Tomi':7, 'Kelly':12, 'Martha':24, 'Barter':9}

# Initialize the dictionary for the new business unit
unitThird = {}
# Update the unitFirst and then unitSecond
unitThird.update(unitFirst)
unitThird.update(unitSecond)

# Print new business unit
# Also, check if unitSecond values overrided the unitFirst values or not
print("Unit Third: ", unitThird)
print("Unit First: ", unitFirst)
print("Unit Second: ", unitSecond)

你会发现,不仅需要先手工生成一个空字典对象,而且当需要包含多个字典内容时,需要执行多次 update 方法。

但是,通过 unpack 操作符,我们可以很便捷地一次性完成所有这些操作:

"""
Desc:
Python program to merge three dictionaries using **kwargs
"""
# Define two existing business units as Python dictionaries
unitFirst = { 'Joshua': 10, 'Ryan':5, 'Sally':20, 'Martha':17, 'Aryan':15}
unitSecond = { 'Versha': 11, 'Tomi':7, 'Kelly':12, 'Martha':24, 'Barter':9}
unitThird = { 'James': 3, 'Tamur':5, 'Lewis':18, 'Daniel':23}

# Merge three dictionaries using **kwargs
unitFinal = {**unitFirst, **unitSecond, **unitThird}

# Print new business unit
# Also, check if unitSecond values override the unitFirst values or not
print("Unit Final: ", unitFinal)
print("Unit First: ", unitFirst)
print("Unit Second: ", unitSecond)
print("Unit Third: ", unitThird)