import collections
from itertools import chain
from collections import OrderedDict
a = OrderedDict([('a', 1), ('b', 2)])
b = OrderedDict([('c', 1), ('d', 2)])
e = OrderedDict(chain(a.items(), b.items()))
print(e, a, b)
a.update(b)
print(a)
d1 = collections.OrderedDict([('a', 1), ('b', 2)])
d2 = collections.OrderedDict([('c', 1), ('d', 2)])
d3 = collections.OrderedDict(list(d1.items()) + list(d2.items()))
print(d3)
python合并有序字典OrderedDict
最新推荐文章于 2025-07-01 10:48:34 发布
这段代码展示了如何使用collections模块中的OrderedDict合并两个有序字典,并通过update方法进行字典更新。首先,通过chain函数将a和b两个OrderedDict的items()合并,创建了新的OrderedDict e。然后,演示了update方法如何将b的键值对添加到a中,保持a的有序性。最后,展示了另一种合并OrderedDict的方式,通过将d1和d2的items转换为列表并合并,创建了OrderedDict d3。
151

被折叠的 条评论
为什么被折叠?



