0

我有一个元组,其中包含一些我想与一个或多个字典匹配的名称。

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)

输出(A, foo)在这两种情况下。

这不是很多代码,但它涉及转换为一个集合,然后做一个交集。我正在研究一些 functools 并没有发现任何有用的东西。

使用标准库或我不知道的内置函数是否有更优化的方法?

谢谢。

4

4 回答 4

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

如果您(像我一样)不喜欢异常,并且假设None不是合法值:

for k in t:
    res = dic.get(k)
    if res is not None:
        return k, res
于 2013-06-11T01:12:47.910 回答
1
def f(d):
  try:
    return next((x, d[x]) for x in t if x in d)
  except StopIteration:
    return ()
于 2013-06-11T01:14:04.133 回答
1
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 ()
于 2013-06-11T01:32:33.663 回答
-1

“try-except”变体是可以的,但我认为它们不适合您的情况。如果您知道 t 只有 2 个值(即: len(t) == 2 是不变的/始终为真),您可以利用这一点并尝试以下操作:

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
于 2013-06-11T02:12:38.060 回答