Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search a list with nested dictionary by dictionary value, returning the index of the list with the dictionary element [duplicate]

If I have a list with some nested dictionaries each containing the same keyset and value type set.

list = [{'a': 1, 'b': 2.0, 'c': 3.0}, 
        {'a': 4, 'b': 5.0, 'c': 6.0}, 
        {'a': 7, 'b': 8.0, 'c': 9.0}]

What is the most pythonic way to return the list index of the first of occurrence of 5.0 within the 'b' dictionary keys, or None if nothing is found?

I know I could iterate and search manually:

#with the list above...

result = None
for dict in list:
  if dict['b'] == 5.0:
    result = list.index(dict)
    break
print result
#(prints 1)


#as another example, same code but searching for a different value in 'b'
result = None
for dict in list:
  if dict['b'] == 6.0:
    result = list.index(dict)
    break
print result
#(prints None)

But this seems rather cumbersome. Thank you in advance.

like image 702
llealloo Avatar asked Sep 01 '25 02:09

llealloo


2 Answers

You can use next() builtin method (this will return None if nothing is found):

lst = [{'a': 1, 'b': 2.0, 'c': 3.0},
       {'a': 4, 'b': 5.0, 'c': 6.0},
       {'a': 7, 'b': 8.0, 'c': 9.0}]

print(next((i for i, d in enumerate(lst) if d['b'] == 5.0), None))

Prints:

1
like image 84
Andrej Kesely Avatar answered Sep 02 '25 17:09

Andrej Kesely


You can filter your data using pandas.

Like this,

import pandas as pd

list = [{'a': 1, 'b': 2.0, 'c': 3.0}, 
    {'a': 4, 'b': 5.0, 'c': 6.0}, 
    {'a': 7, 'b': 8.0, 'c': 9.0}]

Put your list into a pandas dataframe,

df = pd.DataFrame(list)

your data

print(df.head())

   a    b    c
0  1  2.0  3.0
1  4  5.0  6.0
2  7  8.0  9.0

and then filter it

df = df[df.b==5]    

and your filtered data,

print(df.head())
   a    b    c
1  4  5.0  6.0

if there is no match, df will be an empty dataframe.

To get just the index,

df.index[df.b==5].tolist()
like image 29
merit_2 Avatar answered Sep 02 '25 17:09

merit_2