Reputation: 95
I've been searching online for a solution, but everything I've done hasn't been working so far. As the title says, I have a dictionary with a list of values stored in it. I need to add those values together. How would I go about doing that? There are about 1000+ keys and values in the dictionary too, this is just a small example.
{'10_Principles_of_Economics': ['13', '13'],'Advanced_ANOVA': ['2', '1', '1', '2'], 'Advanced_Classical_Mechanics': ['1', '1', '1', '1', '1', '1'], 'Agile_software_development': ['1', '2']}
This is what I tried:
def convert_to_dict(matches):
dictionary = dict()
[dictionary[t[0]].append(t[1]) if t[0] in (dictionary.keys())
else dictionary.update({t[0]: [t[1]]}) for t in matches]
print(dictionary)
return dictionary
def sum_dictionary(dictionary):
dd3 = {}
for key in dictionary:
dd3[key] = [sum(dictionary[key])]
I know there is something wrong here, but I'm not completely sure what. Any help would be appreciated.
Upvotes: 0
Views: 45
Reputation: 6132
This should do:
dd4 = {k:sum([int(v) for v in val]) for k,val in dd3.items()}
{'10_Principles_of_Economics': 26,
'Advanced_ANOVA': 6,
'Advanced_Classical_Mechanics': 6,
'Agile_software_development': 3}
Your final function would look like this:
def sum_dictionary(dictionary):
return {k:sum([int(v) for v in val]) for k,val in dictionary.items()}
Please tell me if there's something you don't understand. Be careful to use the same variables in your function definition as the ones inside it.
If you want the sum on a list as strings (as stated in your comment), just change this:
{k:[str(sum([int(v) for v in val]))] for k,val in d.items()}
{'10_Principles_of_Economics': ['26'],
'Advanced_ANOVA': ['6'],
'Advanced_Classical_Mechanics': ['6'],
'Agile_software_development': ['3']}
Upvotes: 1
Reputation: 2267
somethig like this:
d = {
'10_Principles_of_Economics': ['13', '13'],
'Advanced_ANOVA': ['2', '1', '1', '2'],
'Advanced_Classical_Mechanics': ['1', '1', '1', '1', '1', '1'],
'Agile_software_development': ['1', '2']
}
Python 3.x
for key, value in d.items():
d[key] = [str(sum([int(x) for x in value]))]
print (d)
Python 2.x
for key, value in d.iteritems():
Upvotes: 0