简体   繁体   中英

Simple solution to get value from dict without knowing its key

Assume there is a dict like:

{
  "State": "CA",
  "County": "Sonoma",
  "Population": 1200
}

And when I want to get the value of State if I only know the value of County , I write the code below and it works fine.

d = {
  "State": "CA",
  "County": "Sonoma",
  "Population": 900
}

def get_value(value_want, value_know):
    value = [ d[value_want] for k, v in d.items() if v == value_know ]
    # return None if list is empty
    return value[0] if value else None

print(get_value("State", "Sonoma"))
# CA

However, is there any simpler way to do this? This code creates a list which seems pointless because what I want is just str value in the dict , not list , but I couldn't come up with other ideas...

Use d.values() and in :

>>> def get_value(d, value_want, value_know):
...     return d[value_want] if value_know in d.values() else None
... 
>>> d = {
  "State": "CA",
  "County": "Sonoma",
  "Population": 900
}
>>> get_value(d, "State", "Sonoma")
'CA'
>>> get_value(d, "State", "Mendocino")

Not sure I fully understood, but assuming you have a list of dictionaries and want to get the first one matching your requirements:

Here is a solution using an iterator. This means you do not have to test all elements for arbitrary long lists:

d1 = {"State": "CA",
      "County": "Sonoma",
      "Population": 1200}
d2 = {"State": "XX",
      "County": "Other",
      "Population": 1200}

l = [d2, d1, d2, d2, d2, d2] # this could be infinite, here we want the second item

from itertools import dropwhile, islice
i = iter(l)
list(islice(dropwhile(lambda x: x['County'] != 'Sonoma', i), 1))[0]['State']

output: CA

If you just want to check the value which you provide exists in the values then you can do it like below. To retrieve the value needed when you have the value_know.

d = {
    "State": "CA",
    "County": "Sonoma",
    "Population": 900
}


def get_value(d, value_want, value_know):
    return d[value_want] if value_know in d.values() else None

print(get_value(d, "State", "Sonoma"))
# CA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM