简体   繁体   English

在不知道其密钥的情况下从字典中获取价值的简单解决方案

[英]Simple solution to get value from dict without knowing its key

Assume there is a dict like:假设有一个像这样的dict

{
  "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.如果我只知道County的值,当我想获得State的值时,我编写了下面的代码,它运行良好。

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...这段代码创建了一个看起来毫无意义的list ,因为我想要的只是dict中的str值,而不是list ,但我想不出其他想法......

Use d.values() and in :使用d.values()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 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.当你有 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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