Answer the question
In order to leave comments, you need to log in
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
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['возраст'])
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 questionAsk a Question
731 491 924 answers to any question