python – Comparing Two Dictionaries Key Values and Returning the Value If Match
python – Comparing Two Dictionaries Key Values and Returning the Value If Match
You need to iterate over the keys in crucial and compare each one against the dishes keys. So a directly modified version of your code.
for key in crucial.keys():
if key in dishes.keys():
print dishes[key]
It could be better stated as (no need to specify .keys):
for key in crucial:
if key in dishes:
print dishes[key]
If youre using Python 3, the keys
method of dictionaries follows the set
interface. That means you can do an intersection of the keys of the two dictionaries using the &
operator.
for key in crucial.keys() & dishes.keys():
print(dishes[key])
Or if you need a list of the values:
result = [dishes[key] for key in crucial.keys() & dishes.keys()]
In Python 2 you could manage the same thing by explicitly creating sets (perhaps from the iterkeys
generator), but probably it would be better to simply do a loop over the keys, like several of the other answer suggest.
Heres a variation on the loop that I dont think Ive seen anyone else do. The outer loop gets both the keys and values from the dishes
dict, so you dont need to separately look up the value by key.
for key, value in dishes.iteritems(): # use items() in Python 3
if key in crucial:
print value
python – Comparing Two Dictionaries Key Values and Returning the Value If Match
using list comprehension is good
[ dishes[x] for x in crucial if dishes.has_key(x) ]
or ,as per gnibbler:
[ dishes[x] for x in crucial if x in dishes ]
this expression will iterate crucial every key in crucial, if key in dishes, it will return the value of same key in dishes , finally, return a list of all match values.
or , you can use this way, (set (crucial) & set(dishes)) return common keys of both set, then iterate this set and return the values in dishes .
[ dishes[x] for x in set (crucial) & set(dishes) ]