Fusdev
Fusdev

Reputation: 127

Compare one Dictionary Key with another Dictionary Value and create a new Dictionary

I want to create a New dictionory by comparing one dictionry key with another dictionory value

i tried with following code but it's not giving expected results

dictionary1 = {a: 1, b: 2}
dictionary2 = {2: d, 1: e}
common_pairs = dict()
for key in dictionary1:
    if (key in dictionary2 and dictionary1[key] == dictionary2[key]):
      common_pairs[key] = dictionary1[key]
print(common_pairs)

I am expecting output like below

{a: e, b: d}

Thanks in Advance!!

Upvotes: 0

Views: 177

Answers (2)

DarrylG
DarrylG

Reputation: 17156

Using dictionary comprehension

# Valid dictionaries (i.e. key strings must be quoted, thus 'a' not a, etc.)
dictionary1 = {'a': 1, 'b': 2}
dictionary2 = {2: 'd', 1: 'e'}


# Dictionary comprehension (replace value in dictionary1 with lookup
# in dictionary2
result = {k:dictionary2[v] for k, v in dictionary1.items() if v in dictionary2}
print(result) # Output: {'a': 'e', 'b': 'd'}

# Alternative--place None when value not in dicstionary2
dictionary1 = {'a': 1, 'b': 2, 'c':3} # value 3 not in dictionary2
dictionary2 = {2: 'd', 1: 'e'}
result = {k:dictionary2.get(v, None) for k, v in dictionary1.items()}
# Output: {'a': 'e', 'b': 'd', 'c': None}

Upvotes: 3

Eric Frigade
Eric Frigade

Reputation: 128

Without dict comprehension :

dictionary1 = {'a': 1, 'b': 2}
dictionary2 = {2: 'd', 1: 'e'}
common_pairs = dict()

for key in dictionary1:
    common_pairs[key] = dictionary2[dictionary1[key]]
print(common_pairs)  # {'a': 'e', 'b': 'd'}

Upvotes: 0

Related Questions