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…
JavaScript
x
3
1
if any(x in my_dict for x in my_list):
2
print set(my_list)&set(my_dict)
3
But it doesn’t do the job.
Advertisement
Answer
(I renamed list
to my_list
and dict
to my_dict
to avoid the conflict with the type names.)
For better performance, you should iterate over the list and check for membership in the dictionary:
JavaScript
1
4
1
for k in my_list:
2
if k in my_dict:
3
print(k, my_dict[k])
4
If you want to create a new dictionary from these key-value pairs, use
JavaScript
1
2
1
new_dict = {k: my_dict[k] for k in my_list if k in my_dict}
2