我有一个元组,其中包含一些我希望与一个或多个字典匹配的名称。
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并没有找到任何有用的东西。
使用我不知道的标准库或内置函数是否有更优化的方法?
感谢。
答案 0 :(得分: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
答案 1 :(得分:1)
def f(d):
try:
return next((x, d[x]) for x in t if x in d)
except StopIteration:
return ()
答案 2 :(得分: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 ()
答案 3 :(得分:-1)
“尝试 - 除外”变体是可以的,但我认为它们不适合您的情况。如果你知道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