将两个字典与一个链接到另一个

时间:2018-03-15 03:13:36

标签: python loops dictionary iterator

我有两个dicts,我想先将键与输入2进行比较,将值与第二个进行比较:

例如关键字ope1与第二个输入比较并输出一个元组('x','1)作为输出中的关键

我们得到值'y'和'z'将它们与第二个列表进行比较,后者显示了y - > 2和z - > 4并生成一个元组列表[('y' - '2'),('z','4')] 如示例中所示

input1 = {'x':['y','z'], 'w':['m','n']}

input2 = {'x':'1','y':'2','w':'3', 'z':'4','m':'100','n':'200'}

#output = {('x','1'):[('y','2'),('z','4')], ('w','3'): [('m','100'),('n','200')]}

3 个答案:

答案 0 :(得分:1)

您可以使用词典理解:

i1 = {'x':['y','z'], 'w':['m','n']}
i2 = {'x':'1','y':'2','w':'3', 'z':'4','m':'100','n':'200'}

d = {(k, i2[k]): [(i, i2[i]) for i in v] for k, v in i1.items()}

# {('w', '3'): [('m', '100'), ('n', '200')],
#  ('x', '1'): [('y', '2'), ('z', '4')]}

答案 1 :(得分:0)

一种方法是遍历input1字典并形成所需的输出。

<强>演示

input1 = {'x':['y','z'], 'w':['m','n']}
input2 = {'x':'1','y':'2','w':'3', 'z':'4','m':'100','n':'200'}

d = {}
for k,v in input1.items():   #iterate over input1
    d[(k, input2[k])] = []   #Create key and list as value.
    for i in v:
        d[(k, input2[k])].append((i, input2[i]))

print(d)

<强>输出:

{('x', '1'): [('y', '2'), ('z', '4')], ('w', '3'): [('m', '100'), ('n', '200')]}

答案 2 :(得分:0)

有很多方法可以实现这一目标:

input1 = {'x':['y','z'], 'w':['m','n']}

input2 = {'x':'1','y':'2','w':'3', 'z':'4','m':'100','n':'200'}

在一行中使用defaultdict

import collections 

d=collections.defaultdict(list)
[d[(i,input2[i])].append((m,input2[m])) for i,j in input1.items() for m in j]

没有任何导入:

 new_dict={}
    for i,j in input1.items():
        for m in j:
            if (i,input2[i]) not in new_dict:
                new_dict[(i,input2[i])]=[(m,input2[m])]
            else:
                new_dict[(i, input2[i])].append((m,input2[m]))
    print(new_dict)

输出:

{('w', '3'): [('m', '100'), ('n', '200')], ('x', '1'): [('y', '2'), ('z', '4')]}