9

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

 3 years ago
source link: https://www.lujun9972.win/blog/2019/08/26/python%E4%B8%AD%E4%BD%BF%E7%94%A8unpack%E6%93%8D%E4%BD%9C%E7%AC%A6%E5%90%88%E5%B9%B6%E5%A4%9A%E4%B8%AA%E5%AD%97%E5%85%B8/index.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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)
('Unit Third: ', {'Joshua': 10, 'Barter': 9, 'Versha': 11, 'Ryan': 5, 'Tomi': 7, 'Aryan': 15, 'Kelly': 12, 'Martha': 24, 'Sally': 20})
('Unit First: ', {'Joshua': 10, 'Martha': 17, 'Sally': 20, 'Aryan': 15, 'Ryan': 5})
('Unit Second: ', {'Kelly': 12, 'Versha': 11, 'Martha': 24, 'Barter': 9, 'Tomi': 7})

你会发现,不仅需要先手工生成一个空字典对象,而且当需要包含多个字典内容时,需要执行多次 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)
Unit Final: {'Tomi': 7, 'Ryan': 5, 'Tamur': 5, 'Versha': 11, 'James': 3, 'Sally': 20, 'Martha': 24, 'Aryan': 15, 'Daniel': 23, 'Barter': 9, 'Lewis': 18, 'Kelly': 12, 'Joshua': 10}
Unit First: {'Joshua': 10, 'Ryan': 5, 'Martha': 17, 'Sally': 20, 'Aryan': 15}
Unit Second: {'Tomi': 7, 'Barter': 9, 'Martha': 24, 'Versha': 11, 'Kelly': 12}
Unit Third: {'Daniel': 23, 'Tamur': 5, 'James': 3, 'Lewis': 18}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK