0

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 を調べていましたが、有用なものは見つかりませんでした。

私が気付いていない標準ライブラリまたは組み込み関数を使用して、これを行うより最適化された方法はありますか?

ありがとう。

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):
    """
    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 は不変/常に 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
于 2013-06-11T02:12:38.060 に答える