compare values from dictionary with list

Question:

i have a dictionary like this and i want to compare it with a list

dic=
{0: 0,
 1: 1200,
 2: 2400,
 3: 1800,
 4: 2400,
 5: 2400,
 6: 1200,
 7: 1800,
 8: 2400}

list = [0,2,5,7]

How can I create sum over the list with the values from the dictionary?

sum = 0+2400+2400+1800

Thanks!

UPDATE

and how is it if I want to compare it with another dictionary instead of the list? so I need a sum for 0 and 1

dic2=
{Route1: [0, 2, 5, 7]
 Route2: [0, 1, 3, 5, 8, 4}

Asked By: chilli93

||

Answers:

You can call dict.get passing 0 as default value for each key in the list, then call sum over it:

>>> sum(dic.get(key, 0) for key in list)
Out[5]: 6600

On a side note, don’t use list as a variable name as it will mask built-in list constructor.

Or, you can use itemgetter from operator, and pass unpacked list, finally use sum for these values. Be noted that you’ll get value error if some keys in list doesn’t exist in dictionary:

>>> from operator import itemgetter
>>> sum(itemgetter(*list)(dic))
Out[8]: 6600
Answered By: ThePyGuy

The simplest approach is:

dic = {0: 0,
       1: 1200,
       2: 2400,
       3: 1800,
       4: 2400,
       5: 2400,
       6: 1200,
       7: 1800,
       8: 2400}

dic2 = {0: [0, 2, 5, 7],
        1: [0, 1, 3, 5, 8, 4]}

results = {}
for key, value in dic2.items():
    total = 0
    for i in value:
        new_value = dic[i]
        total += new_value

    results.update({f'Route{key+1}': total})

print(results)

I suggest you always write the simplest code possible. Unnecessarily complex code, is bad code:

Simple is better than complex.

From the Zen of Python.

Answered By: Riya

For the first case, you can use this:

dic= {  0: 0,
        1: 1200,
        2: 2400,
        3: 1800,
        4: 2400,
        5: 2400,
        6: 1200,
        7: 1800,
        8: 2400
    }

lst = [0,2,5,7]

res = sum(map(lambda x: dic[x], lst))

print(res)

# 6600

And for the second case, use list comprehension:

dic= {  0: 0,
        1: 1200,
        2: 2400,
        3: 1800,
        4: 2400,
        5: 2400,
        6: 1200,
        7: 1800,
        8: 2400
    }

dic2 = {'Route1': [0, 2, 5, 7],
        'Route2': [0, 1, 3, 5, 8, 4]}

lst2 = [sum(map(lambda x: dic[x], dic2[i])) for i in dic2]

print(lst2)

# [6600, 10200]

Or dict comprehension:

dic= {  0: 0,
        1: 1200,
        2: 2400,
        3: 1800,
        4: 2400,
        5: 2400,
        6: 1200,
        7: 1800,
        8: 2400
    }

dic2 = {'Route1': [0, 2, 5, 7],
        'Route2': [0, 1, 3, 5, 8, 4]}

dic3 = {k: sum(map(lambda x: dic[x], dic2[k])) for k in dic2}

print(dic3)

# {'Route1': 6600, 'Route2': 10200}
Answered By: Arifa Chan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.