简体   繁体   中英

how to get the dictionary with a given value in a list of dictionary in python?

I have a list of dictionary, for example my given key value is 'jerry'.

Is there a way to loop to the list and return only dictionary with the key value name of 'jerry'?

lst= [{'name':'tom','score':5},{'name':'jerry','score':10},{'name':'jason','score':8}]

It should return

{'name':'jerry','score':10}

You can get all suitable elements with a generator expression and pick the first with next :

next(d for d in lst if d['name'] == 'jerry')

Use a list comprehension:

result = [x for x in lst if x['name'] == 'jerry'][0]

As a side note, you may want to use a namedtuple for your data if you're going to have a lot of similarly structured dictionaries and you don't want to mutate them:

Person = collections.namedtuple('Person', 'name score')
lst = [Person('jerry', 10), ...]
result = [x for x in lst if x.name == 'jerry'][0] 

A list comprehension should work:

lst = [{'name':'tom','score':5},{'name':'jerry','score':10},{'name':'jason','score':8}]
print([d for d in lst if d['name'] == 'jerry'][0])

Note that you can also use filter method

lst = [{'name':'tom','score':5},{'name':'jerry','score':10},{'name':'jason','score':8}]
filter(lambda x: x.get('name') == 'jerry', lst)

OR create lambda:

getUserDataByName = lambda userName: filter(lambda x: x.get('name') == userName, lst)

OR:

getData = lambda propName, propVal: filter(lambda x: x.get(propName) == propVal, lst)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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