Home > Enterprise >  how do i use more than 1 list index?
how do i use more than 1 list index?

Time:04-22

how do i use more than 1 list index? like i wanna search through more than just 0 without writing another line that then searches 1, that feels like a workaround

This is my current code, I'm using an API that then I put into a json

>result = response.json()

>{'exercises': [{'tag_id': 317, 'user_input': 'run', 'duration_min': 30, 'met': 9.8, 'nf_calories': 842.8, 'photo': {'highres': 'https://d2xdmhkmkbyw75.cloudfront.net/exercise/317_highres.jpg', 'thumb': 'https://d2xdmhkmkbyw75.cloudfront.net/exercise/317_thumb.jpg', 'is_user_uploaded': False}, 'compendium_code': 12050, 'name': 'running', 'description': None, 'benefits': None}, {'tag_id': 814, 'user_input': 'bike', 'duration_min': 1, 'met': 6.8, 'nf_calories': 19.49, 'photo': {'highres': None, 'thumb': None, 'is_user_uploaded': False}, 'compendium_code': 1020, 'name': 'bicycling', 'description': None, 'benefits': None}]}

then I'm trying to get the 'name', but theres two instances of name and i can only use 0,1,2 etc as the index

>exercises = result['exercises'][0]['name']
>exercisess = result['exercises'][1]['name']
>print(exercises)
>print(exercisess)
>running
>bicycling

is there a way i can search whole thing for keys and get their value without specifically saying 0,1,2 as the index to search

I'm a noob at this sorry if i formatted this question wrong.

CodePudding user response:

You can use list comprehension to add them all to a list then print that.

data = {'exercises': [{'tag_id': 317, 'user_input': 'run', 'duration_min': 30, 'met': 9.8, 'nf_calories': 842.8, 'photo': {'highres': 'https://d2xdmhkmkbyw75.cloudfront.net/exercise/317_highres.jpg', 'thumb': 'https://d2xdmhkmkbyw75.cloudfront.net/exercise/317_thumb.jpg', 'is_user_uploaded': False}, 'compendium_code': 12050, 'name': 'running', 'description': None, 'benefits': None}, {'tag_id': 814, 'user_input': 'bike', 'duration_min': 1, 'met': 6.8, 'nf_calories': 19.49, 'photo': {'highres': None, 'thumb': None, 'is_user_uploaded': False}, 'compendium_code': 1020, 'name': 'bicycling', 'description': None, 'benefits': None}]}
names = [x['name'] for x in data['exercises']]
print(names)

# output: ['running', 'bicycling']

Depends on what you are after.

CodePudding user response:

You use a for loop:

for ex in result['exercises']:
    print(ex['name'])

The name ex will refer to each of the elements in turn.

  • Related