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.
合并两个字典的不同方法 (Different ways of merging two dictionaries)
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中的值。
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中的值。
d1={
'a':1,'b':2}
d2={
'a':99,