K
K
kirrik0072019-08-31 14:18:46
Python
kirrik007, 2019-08-31 14:18:46

Data aggregation from a Python dictionary?

There is a list: [{'name': 'Ivan', 'age': '23'}, {'name': 'Ivan', 'age': '25'}, {'name': 'Peter', ' age': '34'}, {'name': 'Peter', 'age': '37'}]
We need to aggregate the data so that the output looks like this: [{'Ivan': ['23', '25' ]}, {'Peter': ['34', '37']}]
How can this be done?
ps Sorry for the question in advance (if it seems "stupid"), but I can't figure out how to organize it...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2019-08-31
@kirrik007

from collections import defaultdict

a =  [
    {'name': 'Иван', 'возраст': '23'},
    {'name': 'Иван', 'возраст': '25'},
    {'name': 'Пётр', 'возраст': '34'},
    {'name': 'Пётр', 'возраст': '37'}
]
d = defaultdict(list)

for i in a:
    d[i['name']].append(i['возраст'])

N
Nyamistaya, 2019-09-17
@Nyamistaya

Why extra libraries?

a =  [
    {'name': 'Иван', 'возраст': '23'},
    {'name': 'Иван', 'возраст': '25'},
    {'name': 'Пётр', 'возраст': '34'},
    {'name': 'Пётр', 'возраст': '37'}
]
d = [{dct.get('name'):dct.get('возраст')} for dct in a]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question