[英]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.