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

时间:2018-11-19 22:58:43

标签: python defaultdict

我有以下默认值:

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)

但是很明显,这没有达到预期的效果。有人可以帮我弄这个吗?谢谢

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

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]