-1

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?

Youness Saadna
  • 792
  • 2
  • 8
  • 25
vUes
  • 23
  • 1
  • 5
  • Does this answer your question? [Python: Find in list](https://stackoverflow.com/questions/9542738/python-find-in-list) – Pranav Hosangadi Aug 10 '20 at 19:58
  • You have to use a loop, one way or another. As an aside, you shouldn't use `dict` objects like this. Of course, often something like this is the result of some JSON, but `dict` objects aren't really record types, they are optimized to be *maps* – juanpa.arrivillaga Aug 10 '20 at 20:00
  • The `Linq` syntax you're used to using in VB.Net is essentially syntactic sugar for a loop – Pranav Hosangadi Aug 10 '20 at 20:01

2 Answers2

0

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)
Jab
  • 26,853
  • 21
  • 75
  • 114
0

try this:

list(filter(lambda d: d['dateB']==value_to_find , list_of_dicts2))
Kuldip Chaudhari
  • 1,112
  • 4
  • 8
  • 1
    Why use `list` and `filter`? Wouldn't a comprehension like `[d for d in list_of_dicts2 if d['dateB'] == value_to_find]` not only be more efficient but way easier to read? – Jab Aug 10 '20 at 20:08
  • Yes it can be done that way also, Will it be more efficient ? Haven't measured and More readable ? Depends on the reader – Kuldip Chaudhari Aug 10 '20 at 20:13
  • 1
    filter is mainly only faster when using small fast functions (usually builtin functions) not lambdas. Plus it has to do 2 lookups for the `list` and `filter` functions and create the lambda function. Comprehensions were made to be more readable and efficient and are the more preferred way over filter in the same manner that map is. – Jab Aug 10 '20 at 20:17
  • Take a look at the answers here: https://stackoverflow.com/questions/3013449/list-comprehension-vs-lambda-filter. It's not a bad answer and I'm not here to create conflict just discussing. – Jab Aug 10 '20 at 20:19
  • Yes, list comprehension works faster on bigger lists. Thanks – Kuldip Chaudhari Aug 10 '20 at 20:28