我有三个决定,如下所示,
d1 = {1:'a',2:'k',3:'l'}
d2 = {1:'j',2:'k',3:'j',4:'n'}
d3 = {1:'j',2:'k',3:'j',4:'i',5:'j'}
有没有一种方法可以合并这三个字典,d1与上面写的d_merged相同,然后d2的相同键通过在d1的最大键中加1来编写,同样来自d3的相同键将被追加在d_merged中通过在d_merged的最大键中添加1,如下所示:
d_merged = {1:'a',2:'k',3:'l',4:'j',5:'k',6:'j',7:'n',8:'j',9:'k',10:'j',11:'i',12:'j'}
答案 0 :(得分:2)
您可以将任务缩减为将两个词典合并为一个,然后使用reduce
和二进制合并功能以合并整个词典列表:
from functools import reduce # Python3, no import needed in Python2
def merge(d1, d2):
mk = max(d1) if d1 else 0 # max key of d1
return dict(list(d1.items()) + [(mk+k, d2[k]) for k in d2])
reduce(merge, [d1, d2, d3]) # reduce dicts
# {1: 'a', 2: 'k', 3: 'l', 4: 'j', 5: 'k', 6: 'j', 7: 'n', 8: 'j', 9: 'k', 10: 'j', 11: 'i', 12: 'j'}
答案 1 :(得分:1)
一个简单的方法:
dicts = [
d1,
{k + max(d1): v for k, v in d2.items()},
{k + max(d2): v for k, v in d3.items()},
]
d_merged = {k: v for d in dicts for k, v in d.items()}
更一般地说:
dicts = [d1, d2, d3]
dicts = ([dicts[0]] +
[{k + max(a): v for k, v in b.items()}
for a, b in zip(dicts[:-1], dicts[1:])])
d_merged = {k: v for d in dicts for k, v in d.items()}
答案 2 :(得分:0)
如何迭代每个字典中的dicts和项目,并使用辅助变量跟踪编号:
d1 = {1:'a',2:'k',3:'l'}
d2 = {1:'j',2:'k',3:'j',4:'n'}
d3 = {1:'j',2:'k',3:'j',4:'i',5:'j'}
d_merged = {}
count = 1
for d in d1, d2, d3:
for k, val in sorted(d.items()):
d_merged[count] = val
count += 1
print(d_merged)
输出如下:
{1: 'a', 2: 'k', 3: 'l', 4: 'j', 5: 'k', 6: 'j', 7: 'n', 8: 'j', 9: 'k', 10: 'j', 11: 'i', 12: 'j'}
答案 3 :(得分:0)
由于订单可能很重要,这里使用OrderedDict
:
from collections import OrderedDict
d1 = {1:'a',2:'k',3:'l'}
d2 = {1:'j',2:'k',3:'j',4:'n'}
d3 = {1:'j',2:'k',3:'j',4:'i',5:'j'}
d1o = OrderedDict(sorted(d1.items(), key=lambda t: t[0]))
d2o = OrderedDict(sorted(d2.items(), key=lambda t: t[0]))
d3o = OrderedDict(sorted(d3.items(), key=lambda t: t[0]))
d_OrderedList=[]
d_OrderedList.extend(d1o.values())
d_OrderedList.extend(d2o.values())
d_OrderedList.extend(d3o.values())
d_merged = OrderedDict()
for i,v in enumerate(d_OrderedList):
d_merged[i+1] = v
输出:
OrderedDict([(1, 'a'), (2, 'k'), (3, 'l'), (4, 'j'), (5, 'k'), (6, 'j'), (7, 'n'), (8, 'j'), (9, 'k'), (10, 'j'), (11, 'i'), (12, 'j')])
print(d_merged)