简体   繁体   中英

Python query on list of dicts

Hello I'm new with python (actually moving from VB)

In VB if I had d list of objects I could do something like this:

    Dim value_to_find = List_of_objects.Where(Function(x) x.Something).FirstOrDefault

on my current project, my data structure is a list of dicts. Something like this:

        [{Id:1,name:Bob, surname:Brown, dateB:07/12/1985,status:Active,code:202020, contact:1,
    list_of_dicts2[{id:1,dateB:07/07/2020},{id:2,dateB:07/08/2020}]}]

Now I want to access a certain dateB in the list_of_dicts2, if there a way to do it like in Visual Basic? or I have to loop through all of it?

You can get the first date matching a condition using the next function and a comprehension.

next(d['dateB'] for d in list_of_dicts if your_condition)

next also allows a default value if none match your condition in the list:

next((d['dateB'] for d in list_of_dicts if your_condition), your_default_value)

try this:

list(filter(lambda d: d['dateB']==value_to_find , list_of_dicts2))

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