-5

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"])
Mashie
  • 41
  • 3

2 Answers2

0
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']

JEFFRIN JACOB
  • 257
  • 1
  • 6
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers here (https://stackoverflow.com/help/how-to-answer) – Buddy Bob Apr 21 '22 at 20:52
-1

Just get i['id'] for each dict in pets

 pet_ids = [i['id'] for i in pets]

Output:

[1, 2, 3, 4]
Emi OB
  • 2,814
  • 3
  • 13
  • 29