471,348 Members | 1,314 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,348 software developers and data experts.

Sum values stored in a dictionary as a list of values.

GTXY20
29
Hi All,

I have the following dictionary:

Expand|Select|Wrap|Line Numbers
  1. {'1': [10, 5, 4, 1], '3': [10, 5, 4, 1], '2': [10, 5, 4, 1], '4': [10, 4]}
I need to sum the values for each key and make the dictionary:

Expand|Select|Wrap|Line Numbers
  1. {'1': [20], '3': [20], '2': [20], '4': [14]}
I have tried:


Expand|Select|Wrap|Line Numbers
  1. for item in f.values():
  2.                 for items in item:
  3.                     sum(items)
I am pretty sure I am way off here any advice where to start.
Oct 5 '07 #1
2 13622
bvdet
2,851 Expert Mod 2GB
Hi All,

I have the following dictionary:

Expand|Select|Wrap|Line Numbers
  1. {'1': [10, 5, 4, 1], '3': [10, 5, 4, 1], '2': [10, 5, 4, 1], '4': [10, 4]}
I need to sum the values for each key and make the dictionary:

Expand|Select|Wrap|Line Numbers
  1. {'1': [20], '3': [20], '2': [20], '4': [14]}
I have tried:


Expand|Select|Wrap|Line Numbers
  1. for item in f.values():
  2.                 for items in item:
  3.                     sum(items)
I am pretty sure I am way off here any advice where to start.
This is one way:
Expand|Select|Wrap|Line Numbers
  1. >>> dd = {'1': [10, 5, 4, 1], '3': [10, 5, 4, 1], '2': [10, 5, 4, 1], '4': [10, 4]}
  2. >>> dd2 = dict(zip(dd.keys(), [[sum(item)] for item in dd.values()]))
  3. >>> dd2
  4. {'1': [20], '3': [20], '2': [20], '4': [14]}
  5. >>> 
another one:
Expand|Select|Wrap|Line Numbers
  1. >>> dd3 = {}
  2. >>> for key in dd:
  3. ...     dd3[key] = [sum(dd[key])]
  4. ...     
  5. >>> dd3
  6. {'1': [20], '3': [20], '2': [20], '4': [14]}
  7. >>> 
You can also update the original:
Expand|Select|Wrap|Line Numbers
  1. >>> for key in dd:
  2. ...     dd[key] = [sum(dd[key])]
  3. ...     
  4. >>> dd
  5. {'1': [20], '3': [20], '2': [20], '4': [14]}
  6. >>> 
Oct 5 '07 #2
GTXY20
29
Perfect!

Thanks so much.
Oct 5 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

5 posts views Thread by j1o1h1n | last post: by
13 posts views Thread by Nader | last post: by
reply views Thread by Maric Michaud | last post: by
1 post views Thread by Ronak mishra | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.