简体   繁体   English

从字典列表中提取一个字典(Python)

[英]Extracting one dictionary from a list of dictionaries (Python)

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:例如,如果输入是“kabuto”,则返回/打印:

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

Is this possible/what is the best way to do this?这可能吗/最好的方法是什么?

You can use a for loop:您可以使用for循环:

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

This outputs:这输出:

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

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM