如何使用新的键组合从 defaultdict 获取值?

How to get values from a defaultdict using a new combination of keys?

我有以下默认指令:

dictA = {"a": {"b": 0.1, "c": 0.2}, "b": {"c": 0.3}}

根据这个字典,我需要使用以下键组合将值附加到列表中:

order = [("b","b"), ("b","a"), ("b","c"), ("a","b", ("a","a"), ("a","c"), ("c","b"), ("c","a"), ("c","c")]

如果组合键相同(例如("a"、"a")),则该值应为零。所以最终结果应该如下所示:

result = [0, 0.1, 0.3, 0.1, 0, 0.2, 0.3, 0.2, 0]

我试过以下方法

 dist = []
 for index1, member1 in enumerate(order):
    curr = dictA.get(member1, {})
    for index2, member2 in enumerate(order): 
        val = curr.get(member2)
        if member1 == member2:
            val = 0
        if member2 not in curr:
            val = None
        dist.append(val)

但显然这没有按预期工作。有人可以帮我弄这个吗?谢谢

你可以这样做:

def get(d, first, second):
    return d.get(second, {}).get(first, 0.0)

dictA = {"a": {"b": 0.1, "c": 0.2}, "b": {"c": 0.3}}
order = [("b", "b"), ("b", "a"), ("b", "c"), ("a", "b"), ("a", "a"), ("a", "c"), ("c", "b"), ("c", "a"), ("c", "c")]

result = [get(dictA, first, second) or get(dictA, second, first) for first, second in order]

print(result)

输出

[0.0, 0.1, 0.3, 0.1, 0.0, 0.2, 0.3, 0.2, 0.0]

或更少的 pythonic 替代方案:

def get(d, first, second):
    return d.get(second, {}).get(first, 0.0)


dictA = {"a": {"b": 0.1, "c": 0.2}, "b": {"c": 0.3}}
order = [("b", "b"), ("b", "a"), ("b", "c"), ("a", "b"), ("a", "a"), ("a", "c"), ("c", "b"), ("c", "a"), ("c", "c")]

result = []
for first, second in order:
    value = get(dictA, first, second)
    if value:
        result.append(value)
    else:
        value = get(dictA, second, first)
        result.append(value)


print(result)

输出

[0.0, 0.1, 0.3, 0.1, 0.0, 0.2, 0.3, 0.2, 0.0]