python建立一个通讯录字典,如何连接两个字典在Python中创建一个新的字典?

本文探讨了三种不同的Python字典合并方法,包括串联items并构造新字典、利用dict构造器和update方法,以及循环更新空字典。通过性能测试,推荐使用dict构造器结合update的方法,因为它在速度上最快且避免了额外的内存消耗。这种方法对于处理大量数据的字典合并尤其重要。
摘要由CSDN通过智能技术生成

Say I have three dicts

d1={1:2,3:4}

d2={5:6,7:9}

d3={10:8,13:22}

How do I create a new d4 that combines these three dictionaries? i.e.:

d4={1:2,3:4,5:6,7:9,10:8,13:22}

解决方案slowest: concatenate the items and call dict on the resulting list:

$ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \

'd4 = dict(d1.items() + d2.items() + d3.items())'

100000 loops, best of 3: 4.93 usec per loop

fastest: exploit the dict constructor to the hilt, then one update:

$ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \

'd4 = dict(d1, **d2); d4.update(d3)'

1000000 loops, best of 3: 1.88 usec per loop

middling: a loop of update calls on an initially-empty dict:

$ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \

'd4 = {}' 'for d in (d1, d2, d3): d4.update(d)'

100000 loops, best of 3: 2.67 usec per loop

or, equivalently, one copy-ctor and two updates:

$ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \

'd4 = dict(d1)' 'for d in (d2, d3): d4.update(d)'

100000 loops, best of 3: 2.65 usec per loop

I recommend approach (2), and I particularly recommend avoiding (1) (which also takes up O(N) extra auxiliary memory for the concatenated list of items temporary data structure).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值