user1893110 user1893110 - 19 days ago 5
Python Question

Extracting values from dictionary using list

Given a list of values e.g.

list1=[19, 25, 100]


and an index:

i = {'a': {10: 1}, 'b': {100: 3}, 'c': {19: 3, 25: 2, 26: 1, 28: 1, 30: 1}, 'd': {46:4, 100: 1}, 'e': {10: 1, 25: 1, 100: 1}, 'f': {4: 1, 19: 1}


What is the least expensive method (dealing with a much larger scale) with which I can look up a list value within the dict's first values, sum all of the second values of the value pairs belonging to the key it appears in and multiply this by the second value itself? I'd want these values to be collated in a structure like so.

{{19: [24, 2], 25: [16, 3], 100: [3, 3, 5]}}


where 24 = (3 * (3+2+1+1+1)) for example

Thank you.

Answer

Here is a double loop solution by looping through the keys and dictionaries, and constructing the dictionary on the go:

result = {}
for k in list1:
    result[k] = []
    for v in i.values():
        if k in v:
            result[k].append(v[k] * sum(v.values()))

result
# {19: [24, 2], 25: [16, 3], 100: [9, 3, 5]}