Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Split list of dicts by key

If I have a bunch of dicts in a list like:

people = [{"name": "Abe", "age": 40},
          {"name": "Bob", "age": 25},
          {"name": "Charles", "age": 32}]

I want to split it so it looks like

names = ["Abe", "Bob", "Charles"]
ages = [40, 25, 32]

I know I can do two separate list comprehensions (ex: names = [person["name"] for person in people] twice), but is there any trick to split this data in a one-liner?

like image 962
Michael Avatar asked Nov 24 '25 11:11

Michael


1 Answers

You can use the zip trick:

>>> names, ages = zip(*(d.values() for d in people))
>>> names
('Abe', 'Bob', 'Charles')
>>> ages
(40, 25, 32)

Note that this will only work on Python 3.7 and later as dictionaries are insertion ordered in those versions.

like image 132
Selcuk Avatar answered Nov 26 '25 01:11

Selcuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!