Dictionary keys match on list; get key/value pair
(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:
for k in my_list: if k in my_dict: print k, my_dict[k]
If you want to create a new dictionary from these key-value pairs, use
new_dict = {k: my_dict[k] for k in my_list if k in my_dict}
Don't use dict
and list
as variable names. They shadow the built-in functions. Assuming list l
and dictionary d
:
kv = [(k, d[k]) for k in l if k in d]
new_dict = dict((k, v) for k, v in dict.iteritems() if k in list)
Turning list into a set set(list)
may yield a noticeable speed increase