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.
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With