473,237 Members | 1,399 Online

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

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 14699
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