前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 合并 dict

Python 合并 dict

作者头像
chuchur
发布2022-10-25 14:45:02
7820
发布2022-10-25 14:45:02
举报
文章被收录于专栏:禅境花园

Python 两个或多个字典(dict)合并(取字典并集)

1、 Python 3.9.0 或更高版本使用|

代码语言:javascript
复制
x = {'C': 11, 'Java': 22}
y = {'Python': 33, 'CJavaPy': 44}
z = x | y
print(z)
注意:TypeError: unsupported operand type(s) for |: 'dict' and 'dict' 这个错误原因是Python是Python 3.9.0之前版本,不支持这个语法。

2、Python 3.5 或更高版本使用**

代码语言:javascript
复制
x = {'C': 11, 'Java': 22}
y = {'Python': 33, 'CJavaPy': 44}
z = {**x, **y}
print(z)

# or
z = dict( x.items() + y.items() )
print(z)

# or
z = dict( x, **y )
print(z)

3、Python 2或 3.4及更低版本使用自定函数

代码语言:javascript
复制
def merge_two_dicts(x, y):
    z = x.copy()   
    z.update(y)    
    return z
x = {'C': 11, 'Java': 22}
y = {'Python': 33, 'CJavaPy': 44}
print(merge_two_dicts(x , y))

4、合并多个字典(dict)

代码语言:javascript
复制
def merge_dicts(*dict_args):
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result
x = {'C': 11, 'Java': 22}
y = {'Python': 33, 'CJavaPy': 44}
z ={'www.cjavapy.com':55,'Linux':66}
print(merge_dicts(x , y, z))

5、性能测试

代码语言:javascript
复制
from timeit import repeat
from itertools import chain
x = dict.fromkeys('https://www.chuchur.com')
y = dict.fromkeys('javascript')
def merge_dicts(*dict_args):
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result
print(min(repeat(lambda: {**x, **y},number=1)))
print(min(repeat(lambda: merge_dicts(x, y),number=1)))
#min(repeat(lambda: x | y)) #python 3.9.0及以上版本
print(min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()},number=1)))
print(min(repeat(lambda: dict(chain(x.items(), y.items())),number=1)))
print(min(repeat(lambda: dict(item for d in (x, y) for item in d.items()),number=1)))
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/08/22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Python 两个或多个字典(dict)合并(取字典并集)
    • 1、 Python 3.9.0 或更高版本使用|
      • 2、Python 3.5 或更高版本使用**
        • 3、Python 2或 3.4及更低版本使用自定函数
          • 4、合并多个字典(dict)
            • 5、性能测试
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档