1

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.

Community
  • 1
  • 1
user
  • 4,651
  • 5
  • 32
  • 60

1 Answers1

2

Provided you know only one key will match:

In [89]: keys = ['name', 'display_name', 'displayName', 'displayname']
         data = {'name': 'Foo', 'baz': 'bim'}
         data[set(keys).intersection(data.keys()).pop()]
Out[89]: 'Foo'

Edit: To explain. pop() for a set returns an arbitrary element, so if you know the intersection of the two sets can only be one element, it will always return what you're looking for.

Adam Acosta
  • 603
  • 3
  • 6