Reputation: 425
I have a list of items that may or may not be keys in a dictionary. There is an order to the items. So I want to go from the first to the last and search for them in the dictionary. The first one to appear in the dictionary is the one that I want the value of. If none are in there, I want None.
I want this in a clean pythonic one liner, since it should be simple. I thought about something like this (but the syntax does not work):
value = dictionary.get(key) for key in list_of_keys while value == None
or maybe with if else like
value = dictionary.get(key) if key in dictionary or list_of_keys == [] else key = list_of_keys.pop()
but the second one only works if I initialize the key.
anyone got a simpler way to do this?
Upvotes: 1
Views: 114
Reputation: 118
A simple solution with linear time complexity would be -
d = dict()
# define your dict here
for k in list_of_keys:
val = d.get(k, None) # you could also use try-except
if val:
print(val)
break
Upvotes: 0
Reputation: 862
You can try this:
value = next((dictionary[key] for key in list_of_keys if key in dictionary), None)
Explanation:
(dictionary[key] for key in list_of_keys if key in dictionary)
will create a python generator.
By using next
, it will stop iterating through the python generator when the first valid key is found. If the generator is empty, it will return the second argument as the default value, in this case, None
.
Upvotes: 3
Reputation: 484
value = [dictionary.get(key) for key in list_of_keys if key in dictionary][0]
This will work so long as there is as the dictionary contains at least one key in list_of_keys. It makes a list of the value of each key in list_of_keys and then [0] only outputs the first one.
Testing:
dictionary=dict(tom=9, bob=8, rose=4)
list_of_keys=['harry', 'sam', 'bob']
value = [dictionary.get(key) for key in list_of_keys if key in dictionary][0]
print(value)
8
Upvotes: 1