Home > Enterprise >  Extracting one dictionary from a list of dictionaries (Python)
Extracting one dictionary from a list of dictionaries (Python)

Time:05-25

I have a list of dicts like this:

[{'name': 'kabuto', 'id': 140},
 {'name': 'articuno', 'id': 144},
 {'name': 'nidorino', 'id': 33}]

I would like to ask my user...

input('Which pokemon do you choose? ')

...and then return/print the one dictionary where user input and name matches.

For example, if input is 'kabuto', then this is returned/printed:

'name': 'kabuto', 'id': 140

Is this possible/what is the best way to do this?

CodePudding user response:

You can use a for loop:

for item in data:
    if item['name'] == 'kabuto':
        print(item)
        break

This outputs:

{'name': 'kabuto', 'id': 140}

CodePudding user response:

It's possible use this way using filters:

pokemons = [{'name': 'kabuto', 'id': 140},
            {'name': 'articuno', 'id': 144},
            {'name': 'nidorino', 'id': 33}]

pokemon = list(filter(lambda p : p['name'] == "kabuto", pokemons))[0]

print(pokemon)
  • Related