目录

1. 最简单的原地更新

2. 先解包再合并字典

3. 借助 itertools

4. 借助 ChainMap

5. 使用dict.items() 合并

6. 最酷炫的字典解析式

7. Python 3.9 新特性


1. 最简单的原地更新

字典对象内置了一个 update 方法,用于把另一个字典更新到自己身上。

>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> profile.update(ext_info)
>>> print(profile)
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

如果想使用 update 这种最简单、最地道原生的方法,但又不想更新到自己身上,而是生成一个新的对象,那请使用深拷贝。

>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> from copy import deepcopy
>>>
>>> full_profile = deepcopy(profile)
>>> full_profile.update(ext_info)
>>>
>>> print(full_profile)
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}
>>> print(profile)
{"name": "xiaoming", "age": 27}

2. 先解包再合并字典

使用 ** 可以解包字典,解包完后再使用 dict 或者 {} 就可以合并。

>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> full_profile01 = {**profile, **ext_info}
>>> print(full_profile01)
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}
>>>
>>> full_profile02 = dict(**profile, **ext_info)
>>> print(full_profile02)
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

若你不知道 dict(**profile, **ext_info) 做了啥,你可以将它等价于

>>> dict((("name", "xiaoming"), ("age", 27), ("gender", "male")))
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

3. 借助 itertools

在 Python 里有一个非常强大的内置模块,它专门用于操作可迭代对象。

正好我们字典也是可迭代对象,自然就可以想到,可以使用 itertools.chain() 函数先将多个字典(可迭代对象)串联起来,组成一个更大的可迭代对象,然后再使用 dict 转成字典。

>>> import itertools
>>>
>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>>
>>> dict(itertools.chain(profile.items(), ext_info.items()))
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

4. 借助 ChainMap

如果可以引入一个辅助包,那我就再提一个, ChainMap 也可以达到和 itertools 同样的效果。

>>> from collections import ChainMap
>>>
>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> dict(ChainMap(profile, ext_info))
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

使用 ChainMap 有一点需要注意,当字典间有重复的键时,只会取第一个值,排在后面的键值并不会更新掉前面的(使用 itertools 就不会有这个问题)。

>>> from collections import ChainMap
>>>
>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info={"age": 30}
>>> dict(ChainMap(profile, ext_info))
{'name': 'xiaoming', 'age': 27}

5. 使用dict.items() 合并

在 Python 3.9 之前,其实就已经有 | 操作符了,只不过它通常用于对集合(set)取并集。

利用这一点,也可以将它用于字典的合并,只不过得绕个弯子,有点不好理解。

你得先利用 items 方法将 dict 转成 dict_items,再对这两个 dict_items 取并集,最后利用 dict 函数,转成字典。

>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> full_profile = dict(profile.items() | ext_info.items())
>>> full_profile
{'gender': 'male', 'age': 27, 'name': 'xiaoming'}

当然了,你如果嫌这样太麻烦,也可以简单点,直接使用 list 函数再合并(示例为 Python 3.x )

>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> dict(list(profile.items()) + list(ext_info.items()))
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

若你在 Python 2.x 下,可以直接省去 list 函数。

>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> dict(profile.items() + ext_info.items())
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

6. 最酷炫的字典解析式

Python 里对于生成列表、集合、字典,有一套非常 Pythonnic 的写法。

那就是列表解析式,集合解析式和字典解析式,通常是 Python 发烧友的最爱,那么今天的主题:字典合并,字典解析式还能否胜任呢?

当然可以,具体示例代码如下:

>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> {k:v for d in [profile, ext_info] for k,v in d.items()}
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

7. Python 3.9 新特性

在 2 月份发布的 Python 3.9.04a 版本中,新增了一个抓眼球的新操作符操作符: |, PEP584 将它称之为合并操作符(Union Operator),用它可以很直观地合并多个字典。

>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> profile | ext_info
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}
>>>
>>> ext_info | profile
{'gender': 'male', 'name': 'xiaoming', 'age': 27}
>>>
>>>

除了 | 操作符之外,还有另外一个操作符 |=,类似于原地更新。

>>> ext_info |= profile
>>> ext_info
{'gender': 'male', 'name': 'xiaoming', 'age': 27}
>>>
>>>
>>> profile |= ext_info
>>> profile
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

python3 dict 字典 合并相关推荐

  1. python3 dict 字典 转 严格 json

    python3中的字典dict格式会将{"a":"1","b":"2"}的格式自动转换为{'a': ' 1', 'b': ...

  2. python3字典合并_Python3.9中的字典合并和更新,几乎影响了所有Python程序员

    全文共2837字,预计学习时长9分钟 Python3.9正在积极开发,并计划于今年10月发布. 2月26日,开发团队发布了alpha 4版本.该版本引入了新的合并(|)和更新(|=)运算符,这个新特性 ...

  3. ​Python3.9中的字典合并和更新,了解一下

    全文共2837字,预计学习时长9分钟 来源:Pexels Python3.9正在积极开发,并计划于今年10月发布. 2月26日,开发团队发布了alpha 4版本.该版本引入了新的合并(|)和更新(|= ...

  4. Python list合并(列表合并),dict合并(字典合并)

    list合并(列表合并) d1 = [1, 2, 3] result = []result.extend(d1) dict合并(字典合并) d1 = {'name': 'revotu', 'age': ...

  5. python字典(dict)合并的操作

    dict介绍: 字典是另一种可变容器模型,且可存储任意类型对象. 字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 ,基本 ...

  6. python3字典操作_(04)-Python3之--字典(dict)操作

    1.定义 字典的关键字:dict 字典由多个键和其对应的值构成的 键-值 对组成,每个键值对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中. {key1:value1 ...

  7. mq3.8.9版本有什么不同_Python3.9版本新特性:字典合并操作的详细解读

    处于测试阶段的Python 3.9版本中有一个新特性:我们在使用Python字典时,将能够编写出更可读.更紧凑的代码啦! Python版本 你现在使用哪种版本的Python?3.7分?3.5分?还是2 ...

  8. python字典转dataframe_python DataFrame转dict字典过程详解

    python DataFrame转dict字典过程详解 这篇文章主要介绍了python DataFrame转dict字典过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习 ...

  9. python3 dict 排序_Python 3.9 新增功能展望

    在Python3.8的首个正式版发布一年后,根据Python发版规律最新的Python版本为3.9,预计将在下个月发布第一个正式版本.那么Python 3.9能带来哪些更新和变化呢,请和虫虫一起展望学 ...

最新文章

  1. 安装centos 7 桌面
  2. gcc 提供的原子操作
  3. Merge、Rebase
  4. OPA 18 - iTeardownMyAppFrame
  5. 文本三剑客之grep
  6. 《机器学习概论》习题答案
  7. mac下一些终端命令的使用
  8. 9206 1225 mybank系统 随堂笔记
  9. 2021-09-18牛客SQL32,SQL33,SQL35,SQL36,SQL37,SQL38,SQL40
  10. QTP统计页面加载时间
  11. ubuntu系统无法连接识别到adb设备和fastboot设备解决方法
  12. javascript createelement_如何创建与框架无关的JavaScript插件
  13. wince6.0 OK6410 启动NandFlash路径下的程序快捷键
  14. AI之语音转写项目实践
  15. Ansys APDL的超声换能器的模态分析(更新中)
  16. 产品经理认证(NPDP)---新产品流程
  17. r语言和pythonjava_python和R语言有什么区别?
  18. java mysql utc时间_Java项目统一UTC时间方案
  19. UML图详解(九)包图
  20. 【HTML/CSS】创建日期和时间表单控件

热门文章

  1. java实现鼠标宏编程_我應該如何編程高級java遊戲中的鼠標/鍵輸入?
  2. AWS — Nitro System
  3. C 家族程序设计语言发展史
  4. Python Module_subprocess_调用 Powershell
  5. Linux_RHEV虚拟化_基础理论KVM
  6. Python_基础知识储备
  7. 51单片机中将变量、数组、函数设置在固定位置,定位到绝对地址
  8. 监控利器Prometheus初探
  9. 软件开发有多少种方式
  10. 在DevExpress中使用CameraControl控件进行摄像头图像采集