helloPeople
helloPeople

Reputation: 47

Trying to Sum Key Value Pairs in a Dictionary

I have been struggling with understanding how to sum values from key value pairs in a dictionary.

Printing the dictionary yields something similar to the following:

print(cust.p)
{datetime.datetime(2018, 2, 8, 0, 0): '18.70', datetime.datetime(2018, 2, 12, 0, 0): '8.63', datetime.datetime(2018, 2, 6, 0, 0): '37.61'}

I am trying to add the values after the colon by trying to pass each key at a time using self.cust.p.keys().

def add_p(self):
     return sum(self.p[self.p.values()]

I am looking for a result that adds the 18.70, 8.63, and 37.61 so that when I call the function, it will return 64.94. I also tried using for loops and values() to no avail.

Thank you for your time.

Upvotes: 2

Views: 965

Answers (3)

Gro
Gro

Reputation: 1683

You are storing values as strings, which causes the sum function to throw an error.

Instead, if the dictionary values are converted from string to float before storing (due to the decimals), the code would work.

To convert strings to float, use the map function and pass the result of that to the sum function.

import datetime
keyval = {datetime.datetime(2018, 2, 8, 0, 0): '18.70', 
          datetime.datetime(2018, 2, 12, 0, 0): '8.63', 
          datetime.datetime(2018, 2, 6, 0, 0): '37.61'}

# map(float, keyval.values()) will convert all values to float
# sum will yield the total having sum all float values
sum(map(float, keyval.values())) 

Upvotes: 1

iz_
iz_

Reputation: 16623

Just self.p.values() should suffice. Because the values are currently strings, you should convert them to a numerical type. In this case, float is most appropriate.

def add_p(self):
    return sum(float(x) for x in self.p.values())

Upvotes: 1

blhsing
blhsing

Reputation: 107040

You can convert the dict values to integers before passing them to the sum function:

def add_p(self):
    return sum(map(int, self.p.values()))

Upvotes: 3

Related Questions