python中合并字典_在python中合并字典的7种不同方式

python中合并字典

合并Python字典(Merging Python dictionaries)

In python, we can merge two dictionaries using different methods. Let’s learn about this in this article.

在python中,我们可以使用不同的方法合并两个字典。 让我们在本文中了解这一点。

Refer to my article for Python dictionaries.

请参阅我的Python词典文章

合并两个字典的不同方法 (Different ways of merging two dictionaries)

Image for post
Image Source: Author
图片来源:作者

1. dict.update()(1. dict.update())

update([other])

update ([ other ])

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

使用来自其他的键/值对更新字典,覆盖现有键。 不返回None

Example 1:Merging two dictionaries d1,d2 having unique keys using the update() method.

示例1:使用update()方法合并具有唯一键的两个字典d1,d2。

d1.update(d2)

d1.update(d2)

Update d1- dictionary with key-value pairs from d1 and d2.

使用来自d1和d2的键值对更新d1-字典。

The return type is None. It will update the original dictionary d1.

返回类型为None 。 它将更新原始字典d1

d1={
       'a':1,'b':2}
d2={ 'c':3,'d':4}
d1.update(d2)
print (d1)
#Output:{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Example 2: Merging two dictionaries having the common keys with different values using an update() method.

示例2:使用update()方法合并具有不同值的公共键的两个字典

d1.update(d2)Update d1- dictionary with key-value pairs from d1 and d2.Keys that are common in both d1 and d2 will contain values from d2.

d1.update(d2)使用d1和d2中的键-值对更新d1-字典.d1和d2中共同的键将包含d2中的值。

Image for post
Image Source: Author
图片来源:作者
d1={
       'a':1,'b':2}
d2={ 'a':99,'c':3,'d':4}
d1.update(d2)
print (d1)
#Output:{'a': 99, 'b': 2, 'c': 3, 'd': 4}

d2.update(d1)

d2.update(d1)

Update d2- dictionary with key-value pairs from d1 and d2. Keys that are common in both d1 and d2 will contain values from d1.

使用d1和d2中的键值对更新d2-字典。 在d1和d2中都通用的键将包含d1中的值。

Image for post
Image Source: Author
图片来源:作者
d1={
       'a':1,'b':2}
d2={ 'a':99,
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值