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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With