1 つ以上の辞書と照合したい名前のタプルがあります。
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 を調べていましたが、有用なものは見つかりませんでした。
私が気付いていない標準ライブラリまたは組み込み関数を使用して、これを行うより最適化された方法はありますか?
ありがとう。