Julie Hardy
Julie Hardy

Reputation: 127

create a dictionary from two other dictionaries with similarity between them

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

Answers (3)

Mateen Ulhaq
Mateen Ulhaq

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()}
  1. We loop through each key (k) and value (xs) in d1.
  2. For each item x in xs, we find a path through d2 if d2 contains x.
  3. We flatten the resulting lists using 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

Blckknght
Blckknght

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

mad_
mad_

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

Related Questions