-2

If i have a list like:

my_list = [1,2,3,4]

and a dictionary like:

my_dict = {'bob':1, 'jane':2, 'fred':17}

And i want to lookup the dictionary key,value using the list, i can do it this way:

In [69]: for i in my_list:
    ...:     for k,v in my_dict.items():
    ...:         if i == v:
    ...:             print(k,v)

which returns:

bob 1
jane 2

but i'm trying to work more with list and dict comprehension, and am struggling to figure out how to do this with comprehension... Any help please?

1 Answers1

6

You could filter my_dict by checking the values against my_list in a dict comprehension

>>> {k:v for k,v in my_dict.items() if v in my_list}
{'bob': 1, 'jane': 2}

but this is generating a new dict, not printing out elements (not sure what your eventual goal is)

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218