Home > Net >  Selecting single value from dictionary with multiple values per key
Selecting single value from dictionary with multiple values per key

Time:04-15

dictionary={'key1': ['value1', 3.20],
            'key2': ['value2', 5.10]}

What i want to do is pull out float values and sum them up so 3.20 5.10 but i can't find right method anywhere. I was told by my 'teacher' that it's supposed to look something like this: print(dictionary.values()[1]), it seems right but doesn't work. Any ideas?

CodePudding user response:

Try this:

result = sum(v for _, v in dictionary.values())

Equivalently:

result = sum(lst[1] for lst in dictionary.values())

This is functional approach:

from operator import itemgetter

result = sum(map(itemgetter(1), dictionary.values()))

If you're a novice and you prefer an approach easier to understand:

result = 0
for lst in dictionary.values():
    result = result   lst[1]

As you can see there are many ways to achieve what you want!

CodePudding user response:

This isn't a dictionary. This is in fact a Set. A dictionary has a form of: {"Key": "value} Try

dictionary={'key1':['value1', 3.20],
            'key2':['value2', 5.10]}
  • Related