How to selectively create a dictionary from an existing one?

Viewed 50

I have two dictionaries like below which have common keys:

dictionary1 = {1: 'a', 2: 'b' , 3: 'c'}
dictionary2 = {1: 'no', 2: 'yes' ,3:'yes'}

I want to create a new dictionary with the key and values of dictionary1 only if the corresponding values of the dictionary2 key has "yes".

Expected output:

{2: 'b', 3: 'c'}

What I have tried:

dictionary1 = {1: 'a', 2: 'b' , 3: 'c'}
dictionary2 = {1: 'no', 2: 'yes' ,3:'yes'}
common_pairs = dict()

for key,value in dictionary2.items():
  for key,v in dictionary1.items():
    if(value == "yes"):
      common_pairs[key] =  v
3 Answers

You don't need a nested for loop. Just a single iteration over dictionary1 items with corresponding O(1) lookup in dictionary2:

With a dict comprehension this would look like:

>>> dictionary1 = {1: 'a', 2: 'b' , 3: 'c'}
>>> dictionary2 = {1: 'no', 2: 'yes' ,3:'yes'}
>>> new = {k: v for k, v in dictionary1.items() if dictionary2[k] == 'yes'}
>>> new
{2: 'b', 3: 'c'}

With a traditional for loop:

>>> new = {}
>>> for k, v in dictionary1.items():
...     if dictionary2[k] == 'yes':
...         new[k] = v
... 
>>> new
{2: 'b', 3: 'c'}

You could do this in a dictionary comprehension:

common_pairs = { key:value for key,value in dictionary1.items()
                           if dictionary2.get(key,"") == "Yes" }

The get function provides a default value if the key is not present. this will prevent errors if a key in dictionary1 is absent from dictionary2.

You can just iterate through dict2, check if the element is in dict1 and that the key is yes, and then add it to the dictionary.

dictionary1 = {1: 'a', 2: 'b' , 3: 'c'}
dictionary2 = {1: 'no', 2: 'yes' ,3:'yes'}
common_pairs = dict()

for key in dictionary2:
    if key in dictionary1 and dictionary2[key] == 'yes':
        common_pairs[key] = dictionary1[key]
Related