-1

I have the following defaultdict:

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

From this dict, I need to append the values to a list using the following combination of keys:

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

If the keys combination are the same (for example ("a", "a")), the value should be zero. So the final result should look something like the following:

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

I have tried the following

 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)

But obviously this is not working as intended. Can someone help me with this? Thank you

1 Answers1

0

You could do something like this:

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)

Output

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

Or the less pythonic alternative:

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)

Output

[0.0, 0.1, 0.3, 0.1, 0.0, 0.2, 0.3, 0.2, 0.0]
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
  • This worked like a charm! I probably tried the less pythonic approach. But I see my mistake now. – Giratina86 Nov 19 '18 at 23:51
  • note that this solution will work as requested (put 0.0 where duplicate keys) only when the "dictA" has no duplicated nested keys (something like: dictA = {"a": {"a": 0.5"}} – Aaron_ab Dec 09 '18 at 11:57