'Is it possible to do a list comprehension of a list of dictionaries? [duplicate]
If anyone knows how to do a list comprehension of this, please do let me know!~ Right now I am trying to extract only the IDs into a list. The method I'm using now is a for loop, just wondering if there is a way to do a list comprehension?
pets = [
{"id": 1, "name": "Nelly", "age": "5 weeks", "bio": "I am a tiny kitten rescued by the good people at Paws Rescue Center. I love squeaky toys and cuddles."},
{"id": 2, "name": "Yuki", "age": "8 months", "bio": "I am a handsome gentle-cat. I like to dress up in bow ties."},
{"id": 3, "name": "Basker", "age": "1 year", "bio": "I love barking. But, I love my friends more."},
{"id": 4, "name": "Mr. Furrkins", "age": "5 years", "bio": "Probably napping."},
]
pet_ids = []
for pet in pets:
pet_ids.append(pet["id"])
Solution 1:[1]
pet_ids = [pet['id'] for pet in pets]
You can loop through the pets list using a standard for loop inside list comprehension and from what the loop returns every iteration (which is the individual dictionary you can get the id by accessing it as pet['id']
Solution 2:[2]
Just get i['id'] for each dict in pets
pet_ids = [i['id'] for i in pets]
Output:
[1, 2, 3, 4]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Emi OB |
