You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中基于键合并OrderedDict与defaultdict(operator库实现遇阻)

解决OrderedDict列表与defaultdict按键合并的问题

嘿,我来帮你搞定这个字典合并的问题!你想要把d里的每个OrderedDict和dd通过id键关联起来,把dd中的数值合并进去对吧?之前用operator库没成功没关系,咱们换个更直接的思路来实现。

先明确你的数据结构

首先先把你的数据定义出来,方便后续操作:

from collections import OrderedDict, defaultdict

# 你的OrderedDict列表
d = [
    OrderedDict([('id', '1'), ('date', '20170101')]),
    OrderedDict([('id', '2'), ('date', '20170102')]),
    OrderedDict([('id', '3'), ('date', '20170102')])
]

# 你的defaultdict
dd = defaultdict(int, {'1': 14, '2': 5, '3': 7})

核心合并方法(修改原列表)

最直观的方式就是遍历d里的每个OrderedDict,通过它的id值作为key去dd中取出对应的数值,然后把这个键值对添加到OrderedDict里:

# 遍历每个OrderedDict,合并dd中的对应值
for item in d:
    # 取出当前OrderedDict的id
    item_id = item['id']
    # 添加合并后的键值对,这里键名可以根据你的需求修改,比如叫'value'或者'count'
    item['count'] = dd[item_id]

执行完这段代码后,你可以打印d看看结果:

for item in d:
    print(item)

输出结果如下:

OrderedDict([('id', '1'), ('date', '20170101'), ('count', 14)])
OrderedDict([('id', '2'), ('date', '20170102'), ('count', 5)])
OrderedDict([('id', '3'), ('date', '20170102'), ('count', 7)])

生成新列表(不修改原数据)

如果你不想改动原来的d列表,而是生成一个新的合并后的列表,可以用列表推导式来实现:

new_merged_list = [
    OrderedDict(list(item.items()) + [('count', dd[item['id']])]) 
    for item in d
]

这样d保持不变,new_merged_list就是合并后的结果。

为什么用operator库没成功?

operator库的工具(比如operator.itemgetter)更多是用于提取键值、排序、比较这类场景,直接用它来实现字典合并并不直观,反而会让代码变得复杂。上面的遍历方法逻辑清晰,也更容易调试,完全能满足你的需求。

内容的提问来源于stack exchange,提问作者Keithx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:26:03