Reputation: 127
I got two dictionary like this :
dict1= {'MO': ['N-2', 'N-8', 'N-7', 'N-6', 'N-9'], 'MO2': ['N0-6'], 'MO3': ['N-2']}
dict2= {'N-2': ['NUMBER1'], 'N0-6': ['NUMBER16'], 'N-9': ['NUMBER33']
I would like to create a dictionary like this
dict3={'MO'['NUMBER1','NUMBER33'], 'MO2':['NUMBER16']}
So I developed this code but when I add the values, it is not working
for ki, vi in dict2.items():
for key, value in (itertools.chain.from_iterable([itertools.product((k, ), v) for k, v in dict3.items()])):
if (ki == v):
print vi
Upvotes: 1
Views: 66
Reputation: 27201
A one-liner. :D
{k: [y for x in xs if x in d2 for y in d2[x]] for k, xs in d1.items()}
k
) and value (xs
) in d1
.x
in xs
, we find a path through d2
if d2
contains x
.y ... for y in d2[x]
.Here's another way to format it that might be easier to understand:
{
k: [
y
for x in xs if x in d2
for y in d2[x]
]
for k, xs in d1.items()
}
Upvotes: 1
Reputation: 104722
You only need to loop over one of the dictionaries:
dict1= {'MO': ['N-2', 'N-8', 'N-7', 'N-6', 'N-9'], 'MO2': ['N0-6'], 'MO3': ['N-2']}
dict2= {'N-2': ['NUMBER1'], 'N0-6': ['NUMBER16'], 'N-9': ['NUMBER33']}
dict3 = {}
for key, subkeys in dict1.items():
for subkey in subkeys:
dict3.setdefault(key, []).extend(dict2.get(subkey, []))
Upvotes: 1
Reputation: 8273
Try this using defatuldict
from collections import defaultdict
d =defaultdict(list)
for k in dict1.keys():
for value in dict1[k]:
temp = dict2.get(value)
if temp:
d[k].append(temp)
Output
defaultdict(list,
{'MO': [['NUMBER1'], ['NUMBER33']],
'MO2': [['NUMBER16']],
'MO3': [['NUMBER1']]})
Upvotes: 0