Using Python 2.7, I am trying to extract a value from a dictionary, where the key is from a list / set of possible values (and assuming that if any key is present in the dictionary, only one of the possible keys is present). For example, I want to grab the "name" value from a dictionary, where the key could be name
, display_name
, displayName
, or displayname
. I could do a bunch of if-elif
statements, but hoping for something more elegant. From these SO answers, I believe I could also do something like:
keys = ['name', 'display_name', 'displayName', 'displayname']
data = {'name': 'Foo',
'baz': 'bim'}
if any(_key in data for _key in keys):
filtered = {k:v for k, v in data.iteritems() if k in keys}
display_name = filtered[filtered.keys()[0]]
While that is definitely better than if-elif
statements, is there a one-liner way to do this? (fill in the ????):
keys = ['name', 'display_name', 'displayName', 'displayname']
data = {'name': 'Foo',
'baz': 'bim'}
if any(_key in data for _key in keys):
display_name = ????
I have a bunch of these pairings to find, so that's why I'm looking for simpler solutions.