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

本文详细介绍了在Python中使用7种不同方法合并字典的技巧,包括update()、deepcopy()、字典解包、collections.ChainMap、itertools.chain()、字典理解和使用dict()构造函数。每种方法都有其适用场景,如是否需要修改原字典、键值对冲突解决策略等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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,'c':3,'d':4}
d2.update(d1)
print (d2)
#Output:{'a': 1, 'c': 3, 'd': 4, 'b': 2}

The return type is None. It only updates the original dictionary (d2).

返回类型为无。 它仅更新原始词典(d2)。

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

2.使用deepcopy()和dict.update() (2. Using deepcopy() and dict.update())

If we don’t want to update the original dictionary means, we can create a copy of the dictionary and update it.

如果我们不想更新原始字典的意思,我们可以创建字典的副本并更新它。

To merge two dictionaries d1 and d2, create deepcopy(d1) as d and then do the update method. In this way, the original dictionary will not be modified.

要合并两个字典d1和d2,请创建deepcopy(d1)作为d ,然后执行update方法。 这样,原始字典将不会被修改。

d=deepcopy(d1)
d.update(d2)

d=deepcopy(d1)
d.update(d2)

Refer to my story for deepcopy.

请参阅我的故事进行深度复制。

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

3. {** d1,** d2} (3. {**d1,**d2})

d3={**d1,**d2}

d3={**d1,**d2}

A double asterisk ** denotes dictionary unpacking. Its operand must be a mapping. Each mapping item is added to the new dictionary. Later values replace values already set by earlier key- pairs and earlier dictionary unpackings.

双星号**表示字典解包。 它的操作数必须是一个映射。 每个映射项都添加到新词典中。 较新的值将替换较早的键对和较早的字典解包已设置的值。

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

Merging two dictionaries having unique keys using **kwargs

使用** kwargs合并具有唯一键的两个字典

d3={**d1,**d2}

d3={**d1,**d2}

It will expand the contents of dictionary d1 and d2 as a collection of key-value pairs and update the dictionary d3.

它将字典值d1和d2的内容​​扩展为键值对的集合,并更新字典d3。

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

Merging two dictionaries having common keys using **kwargs

使用** kwargs合并具有公共密钥的两个字典

d3={**d1,**d2}

d3={**d1,**d2}

It will expand the contents of dictionary d1 and d2 as a collection of key-value pairs and update the dictionary d3. Keys that are common in both d1 and d2 will contain values from d2.

它将字典值d1和d2的内容​​扩展为键值对的集合,并更新字典d3。 d1和d2中共同的键将包含d2中的值。

If d3={**d2,**d1} -Keys that are common in both d1 and d2 will contain values from d1.

如果d3={**d2,**d1}在d1和d2中通用的键将包含d1中的值。

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

Merging more than two dictionaries using **kwargs

使用** kwargs合并两个以上的词典

d4={**d1,**d2,**d3}

d4={**d1,**d2,**d3}

It will expand the contents of dictionary d1,d2,d3 as a collection of key-value pairs, and update the dictionary d4.

它将扩展字典d1,d2,d3的内容作为键值对的集合,并更新字典d4。

Keys that are common in d1 and d2 will contain values from d2.Keys that are common in d1 and d3 will contain values from d3.Keys that are common in d1,d2, and d3 will contain values from d3.

在d1和d2中通用的键将包含d2中的值。在d1和d3中通用的键将包含d3中的值。在d1,d2和d3中通用的键将包含d3中的值。

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

4. dict(d1,** d2) (4. dict(d1,**d2))

d3=dict(d1,**d2)

d3 = dict(d1,** d2)

d3 will contain key-value pair from d1 and d2.Keys that are common in d1 and d2 will contain values from d2.

d3将包含d1和d2中的键-值对.d1和d2中公用的键将包含d2中的值。

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

d3=dict(d1,**d2)-This will work only when d2 is entirely string-keyed.

d3 = dict(d1,** d2)-这仅在d2完全用字符串键输入时才有效。

If int is given as a key in d2, it will raise TypeError.

如果在d2中将int作为键给出,它将引发TypeError

d1={'a':1,'b':2}
d2={'a':99,1:3}
d3=dict(d1,**d2)
print (d3)
#Output:TypeError: keywords must be strings

d1 need not be string-keyed. Given int as a key for d1.

d1不需要是字符串键。 以int作为d1的键。

d1={'a':1,1:2}
d2={'a':99,'c':3}
d3=dict(d1,**d2)
print (d3)
#Output:{'a': 99, 1: 2, 'c': 3}

5. collections.ChainMap (5. collections.ChainMap)

ChainMap:A ChainMap group’s multiple dictionary or other mappings together to create a single, updateable view.

ChainMap: ChainMap组的多个词典或其他映射一起创建一个可更新的视图。

collections.ChainMap(*maps)

collections.ChainMap(*maps)

Return Type is collections.ChainMap.We can convert to dict using the dict() constructor.

返回类型为collections.ChainMap。 我们可以使用dict()构造函数转换为dict。

Image for post
Image Source: Author
图片来源:作者
d3=ChainMap(d1,d2)

keys which are common in d1 and d2 will have values from d1(first seen values)

在d1和d2中通用的键将具有d1中的值(首次看到的值)

Merging two dictionaries having unique keys using collections.ChainMap.

使用collections.ChainMap合并具有唯一键的两个字典。

from collections import ChainMap
d1={'a':1,'b':2}
d2={'c':3,'d':4}
d3=ChainMap(d1,d2)
print (d3)
#Output:ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4})print (dict(d3))
#Output:{'c': 3, 'd': 4, 'a': 1, 'b': 2}

Merging two dictionaries having the same keys. The keys which are common in d1 and d2 will contain values from d1 only(first seen value)

合并具有相同键的两个字典。 在d1和d2中通用的键将仅包含d1中的值(首次看到的值)

from collections import ChainMap
d1={'a':1,'b':2}
d2={'c':3,'d':4,'a':99}
d3=ChainMap(d1,d2)
print (d3)
#Output:ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4, 'a': 99})print (dict(d3))
#Output:{'c': 3, 'd': 4, 'a': 1, 'b': 2}

6.itertools.chain(): (6.itertools.chain():)

Makes an iterator that returns an element from the first iterable until its exhausted, then proceeds to the next iterable. It will treat consecutive sequences as a single sequence.itertools.chain(*iterables)

使一个迭代器从第一个可迭代的元素返回直到元素耗尽为止,然后进行到下一个可迭代的元素。 它将连续序列视为单个序列。 itertools.chain(*iterables)

Dictionary is also iterable, so we can use itertools.chain() to merge two dictionaries. The return type will be itertools.chain object. We can convert to dict using the dict() constructor.

字典也是可迭代的,因此我们可以使用itertools.chain()合并两个字典。 返回类型将是itertools.chain对象。 我们可以使用dict()构造函数转换为dict。

Merging two dictionaries having unique keys using itertools.chain()

使用itertools.chain()合并具有唯一键的两个字典

import itertools
d1={'a':1,'b':2}
d2={'c':3,'d':4}
l1=itertools.chain(d1.items(),d2.items())
#Returns an iterator object
print (l1)
#Output:<itertools.chain object at 0x029FE4D8>
#converting iterator object to dict object
print(dict(l1))
#Output:{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Merging two dictionaries having common keys using itertools.chain()

使用itertools.chain()合并具有公共密钥的两个字典

Image for post
Image Source: Author
图片来源:作者
import itertools
d1={'a':1,'b':2}
d2={'a':99,'d':4}
l1=itertools.chain(d1.items(),d2.items())
#Returns an iterator objectprint (l1)
#Output:<itertools.chain object at 0x029FE4D8>
#converting iterator object to dict object
print(dict(l1))
#Output:{'a': 99, 'b': 2, 'd': 4}

7.字典理解 (7. Dictionary Comprehension)

We can merge two dictionaries using dictionary comprehension.

我们可以使用字典理解合并两个字典。

Refer to my story of dictionary comprehension.

请参阅我的字典理解故事

Merging two dictionaries having common keys using dictionary comprehension

使用字典理解合并两个具有共同键的字典

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

Merging two dictionaries having unique keys using dictionary comprehension

使用字典理解合并两个具有唯一键的字典

d1={'a':1,'b':2}
d2={'c':3,'d':4}d3={k:v for d in (d1,d2) for k,v in d.items()}
print (d3)
#Output:{'a': 1, 'b': 2, 'c': 3, 'd': 4}

结论 (Conclusion)

  • Python version used in all examples: Python 3.8.1

    所有示例中使用的Python版本: Python 3.8.1

  • d1.update(d2) -Return type is None.It will update the original dictionary itself(d1).

    d1.update(d2)-返回类型为None它将更新原始字典本身(d1)。

  • {**d1,**d2} — Return type is dictionary.

    {** d1,** d2} -返回类型为dictionary

  • collections.ChainMap- Return type is collections.ChainMap.

    collections.ChainMap-返回类型为collections.ChainMap.

  • itertools.chain() -The return type is itertools.chain object

    itertools.chain() -返回类型为itertools.chain object

  • dict(d1,**d2)-This will work only when d2 is entirely string-keyed.

    dict(d1,** d2) -仅在d2完全用字符串键输入时才有效。

  • “last seen wins” — last seen values will overwrite the existing keys.

    “最后一次看到的胜利” -最后一次看到的值将覆盖现有键。

1. d1.update(d2)
2. {**d1,**d2}
3. dict(d1,**d2)
4. itertool.chain()
5. dictionary comprehension.
  • “first seen wins” instead of “last seen wins”

    “第一次看到的胜利”而不是“最后一次看到的胜利”

1. collections.ChainMap

1. collections.ChainMap

翻译自: https://levelup.gitconnected.com/7-different-ways-to-merge-dictionaries-in-python-30148bf27add

python中合并字典

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值