Katsu
Katsu

Reputation: 111

Dictionary comprehension matching values?

I have this dictionary:

Dict1= {'0': [('L', 'Any'), ('D', 'Any')],
 '1': [('D', 'Any'), ('E', 'Any'), ('D', 'Any')]}

and this one:

Dict2= {'0': ['0', '1', '2'],
 '1': ['0', '1', '2'],
 '2': ['0', '1', '2'],
 '3': ['0', '1', '2']}

I would like to match the key of dict 1 with the value of dict 2 and get this expected output:

NewDict = {'0': [[('L', 'Any'), ('D', 'Any')],
  [('D', 'Any'), ('E', 'Any'), ('D', 'Any')]],
 '1': [[('L', 'Any'), ('D', 'Any')],
  [('D', 'Any'), ('E', 'Any'), ('D', 'Any')]],
 '2': [[('L', 'Any'), ('D', 'Any')],
  [('D', 'Any'), ('E', 'Any'), ('D', 'Any')]],
 '3': [[('L', 'Any'), ('D', 'Any')],
  [('D', 'Any'), ('E', 'Any'), ('D', 'Any')]]}

I have tried this code:

NewDict= {k: [Dict1[e] for e in v] for k, v in Dict2.items()}

But I got the error: KeyError: '2' I know it comes from the value 2 in dict2 who doesn't have any corresponding value but I have to keep it in this form. Is there any way to solve this without modifications of dict2 ? Thank you

Upvotes: 2

Views: 337

Answers (1)

python_user
python_user

Reputation: 7083

Your dict comprehension is almost correct. You needed an if condition to check if the key exists in Dict_1.

Dict1= {'0': [('L', 'Any'), ('D', 'Any')],
 '1': [('D', 'Any'), ('E', 'Any'), ('D', 'Any')]}


Dict2= {'0': ['0', '1', '2'],
 '1': ['0', '1', '2'],
 '2': ['0', '1', '2'],
 '3': ['0', '1', '2']}



NewDict = {k:[Dict1[i] for i in v if i in Dict1] for k, v in Dict2.items()}

print(NewDict)

Output

{'0': [[('L', 'Any'), ('D', 'Any')],
       [('D', 'Any'), ('E', 'Any'), ('D', 'Any')]],
 '1': [[('L', 'Any'), ('D', 'Any')],
       [('D', 'Any'), ('E', 'Any'), ('D', 'Any')]],
 '2': [[('L', 'Any'), ('D', 'Any')],
       [('D', 'Any'), ('E', 'Any'), ('D', 'Any')]],
 '3': [[('L', 'Any'), ('D', 'Any')],
       [('D', 'Any'), ('E', 'Any'), ('D', 'Any')]]}

Upvotes: 4

Related Questions