J
J
justdani2018-02-05 16:20:46
Python
justdani, 2018-02-05 16:20:46

Add the values ​​​​of the same keys of a set of dictionaries united by a list?

We have a list of dictionaries:
a = ({'Petya': 6, 'Vasya': 8, 'Dima': 11, 'Julia': 3}, {'Petya': 5, 'Vasya': 36, 'Dima' : 4, 'Julia': 8}, {'Petya': 54, 'Vasya': 21, 'Dima': 22, 'Julia': 39}, {'Petya': 61, 'Vasya': 48, ' Dima': 71, 'Yulia': 73})
It is necessary to make a dictionary like this:
b = {'Petya': 'Sum of all values ​​from the dictionaries of the list', 'Vasya': 'Sum of all values ​​from the dictionaries of the list', 'Dima': 'Sum of all values ​​from the list's dictionaries', 'Yulia': 'Sum of all the values ​​from the list's dictionaries'}
I've been sitting for half a day trying to figure out an algorithm, any ideas guys?
Correction: Names are not static, values ​​are not static either.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
JaxxDexx, 2018-02-05
@justdani

from collections import Counter

a = ({'Петя': 6, 'Вася': 8, 'Дима': 11, 'Юля': 3}, {'Петя': 5, 'Вася': 36, 'Дима': 4, 'Юля': 8}, {'Петя': 54, 'Вася': 21, 'Дима': 22, 'Юля': 39}, {'Петя': 61, 'Вася': 48, 'Дима': 71, 'Юля': 73})
c = Counter()
for d in a:
    c.update(d)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question