2025年6月5日 星期四 乙巳(蛇)年 三月初九 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

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

时间:12-14来源:作者:点击数:4

当想要创建一个包含多个字典内容的 新字典 对象时,最直观的方法就是调用字典对象的 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}
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐