简体   繁体   English

给出一个名字元组,返回在字典中找到的键名和值

[英]Return the key name and value found in a dictionary given a tuple of names

I have a tuple with some names I want to match against one or more dictionaries. 我有一个元组,其中包含一些我希望与一个或多个字典匹配的名称。

t = ('A', 'B')
d1 = {'A': 'foo', 'C': 'bar'}
d2 = {'A': 'foo', 'B': 'foobar', 'C': 'bar'}

def f(dict):
    """
    Given t a tuple of names, find which name exist in the input
    dictionary dict, and return the name found and its value.
    If all names in the input tuple are found, pick the first one
    in the tuple instead.
    """
    keys = set(dict)
    matches = keys.intersection(t)
    if len(matches) == 2:
        name = t[0]
    else:
        name = matches.pop()
    value = dict[name]
    return name, value


print f(d1)
print f(d2)

The output is (A, foo) in both cases. 两种情况下的输出都是(A, foo)

This is not a lot of code, but it involves converting to a set, and then do an intersection. 这不是很多代码,但它涉及转换为集合,然后进行交集。 I was looking into some functools and haven't found anything useful. 我正在研究一些functools并没有找到任何有用的东西。

Is there a more optimized way doing this using the standard library or built-in functions that I am not aware of? 使用我不知道的标准库或内置函数是否有更优化的方法?

Thanks. 谢谢。

for k in t:
    try:
        return k, dic[k]
    except KeyError:
        pass

If you (like me) don't like exceptions, and assuming None is not a legitimate value: 如果您(像我一样)不喜欢异常,并假设None不是合法值:

for k in t:
    res = dic.get(k)
    if res is not None:
        return k, res
def f(d):
  try:
    return next((x, d[x]) for x in t if x in d)
  except StopIteration:
    return ()
def f(d):
    """
    Given t a tuple of names, find which name exist in the input
    dictionary d, and return the name found and its value.
    If all names in the input tuple are found, pick the first one
    in the tuple instead.
    """
    for item in ((k, d[k]) for k in t if k in d):
        return item
    return ()

The "try-except" variants are ok, but i don't think they are optimal for your case. “尝试 - 除外”变种是可以的,但我认为它们不适合您的情况。 If you know that t has only 2 values (ie: len(t) == 2 is invariant/is always True), you can get advantage of this and try something like this: 如果你知道t只有2个值(即:len(t)== 2是不变的/总是为True),你可以利用这个并尝试这样的事情:

def f(t, dic):
    if t[0] in dic:
        return t[0], dic[t[0]]
    elif t[1] in dic:
        return t[1], dic[t[1]]
    else: # Maybe any of t values are in dict
        return None, None

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

相关问题 在给定 integer 的字典中查找值,可以在字典的元组键之间找到 - Finding value in dict given an integer that can be found in between dictionary's tuple key 无论元组元素的顺序如何,都返回字典键(元组)的值 - return the value for a dictionary key (tuple), irregardless of order of the tuple elements 如何在方法 - 字典中返回给定键的值 - How to return the value of given key in method - dictionary 返回字典中给定元组键元素的最大值 - Return the largest value of a given element of tuple keys in a dictionary 返回字典中第三个值最小的元组对应的键 - Return key corresponding to the tuple with smallest third value from dictionary 返回与其元组的第二个元素中的最大值链接的字典键 - Return the dictionary key linked with max value in the second element of its tuple 获取给定元组键的字典中的最大值,其中元组的元素可能位于不同的位置 - Get maximum value in dictionary for a given tuple key where elements of the tuple may be in different positions 在字典元组键值上拆分数据帧/字典 - Splitting dataframe/dictionary on dictionary tuple key value 如何返回给定特定值的字典中的上一个键? - How to return to previous key in dictionary given a specific value? Python 在字典中搜索字符串值,如果找到则返回键和值 - Python search for string values within dictionary and return key and value if found
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM