简体   繁体   English

从键列表中获取dict中的第一个值

[英]Get first value in dict from a list of keys

Let's suppose that I have the following set :假设我有以下set

labels = set(["foo", "bar"])

And I have a dict with theses values我有一个带有这些价值观的dict

d = {
  "foo": "some value",
  "asdf": "another value",
}

How can I get the first value of the dictionary based on any value of the set labels ?如何根据设置labels的任何值获取字典的第一个值?

In other words, how can I get the value "some value" from the values of the set?换句话说,我怎样才能从集合的值中获得“某个值”的值?

You can apply next() with generator expression :您可以将next()生成器表达式一起应用:

result = next(d[k] for k in labels if k in d)

Upd.更新。 Code above works but it doesn't fit 100%, because it iterates over labels and retrieve value of first key, which not always first occurrence.上面的代码有效,但不是 100%,因为它遍历labels并检索第一个键的值,这并不总是第一次出现。

To get value of first occurrence of any key from labels use next code:要从labels中获取第一次出现的任何键的值,请使用下一个代码:

result = next(v for k, v in d.items() if k in labels)
for key in d:
    if key in labels:
        print(d[key])
        break

Use list comprehension and select the element with 0th index.使用列表理解和 select 具有第 0 个索引的元素。 You may want to wrap this in try...except to catch the case where no element is found in the dictionary.您可能希望将其包装在try...except中,以捕获在字典中未找到任何元素的情况。

labels = set(["foo", "bar"])
d = {
    "foo": "some value",
    "asdf": "another value",
}
print([d[k] for k in labels if k in d][0])
# some value

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

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