Python dictionary sum of all values

 

By sum and values() functions in dictionary we can get sum of all values.

Lets say we have a dictionary d defined as following:

d = {'a' : 1, 'b' : 2, 'c' : 3}

To print sum of all values in above dictionary use following function:

sum(d.values())

Output:

6

To print only values from dictionary:

d.values()

Output:

We will get output as list

[1, 3, 2]

To print only keys from dictionary:

d.keys()

Output:

We will get output as list

[‘a’, ‘c’, ‘b’]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s