Dictionary keys match on list; get key/value pair

Viewed 84358

In python... I have a list of elements 'my_list', and a dictionary 'my_dict' where some keys match in 'my_list'.

I would like to search the dictionary and retrieve key/value pairs for the keys matching the 'my_list' elements.

I tried this...

    if any(x in my_dict for x in my_list):
          print set(my_list)&set(my_dict)

But it doesn't do the job.

6 Answers

Here is a one line solution for that

{i:my_dict[i] for i in set(my_dict.keys()).intersection(set(my_list))}
Related