user7287328
user7287328

Reputation: 11

Combine two dictionaries with list values from one dictionary linked to keys of another

I have two dicts , and I want compare the key first and value second with input 2 :

exampal like key ope1 compare with second input and output a tuple ('x','1) as key in the out put

we come to the value 'y' and 'z' compare them to second list which shown y --> 2 and z--> 4 and produce a list of tuple [(‘y’-‘2’), (‘z’,‘4’)] as shown in the example

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')]}

Upvotes: 0

Views: 47

Answers (3)

Aaditya Ura
Aaditya Ura

Reputation: 12679

There are many ways to achieve this :

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

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

with defaultdict in one line

import collections 

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

without any import :

 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)

output:

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

Upvotes: 0

jpp
jpp

Reputation: 164773

You can use a dictionary comprehension for this:

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')]}

Upvotes: 1

Rakesh
Rakesh

Reputation: 82785

One approach is to iterate over your input1 dictionary and form the required output.

Demo

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)

Output:

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

Upvotes: 0

Related Questions