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}