Find the index in a vector of dictionaries based on the value

0

If I have an array of dictionaries and want to find the index in the array of a certain dictionary value, how do I do it?

Ex:

palavra1 = {'palavra': 'valor1'}
palavra2 = {'palavra': 'valor2'}
palavras = [palavra1, palavra2]

If I want to find what is the index in 'words' that corresponds to 'value2', how should I proceed?     

asked by anonymous 14.06.2018 / 23:22

2 answers

0

To check if the value of the 'word' key corresponds to 'value2':

palavra1.get('palavra') == 'valor2'  # True

This prevents you from having a KeyError for accessing a key that does not exist.

Knowing this, you can loop it through your list and find a valid result:

palavra1 = {'palavra': 'valor1'}
palavra2 = {'palavra': 'valor2'}
palavras = [palavra1, palavra2]

for indice, palavra in enumerate(palavras):
    if palavra.get('palavra') == 'valor2':
        break

print('Indice:', indice)  # 1
print('Palavra:', palavra)  #  {'palavra': 'valor2'}

You can also do the same with a generating expression:

palavra1 = {'palavra': 'valor1'}
palavra2 = {'palavra': 'valor2'}
palavras = [palavra1, palavra2]

indice, palavra = next((i, p) for i, p in enumerate(palavras) if p.get('palavra') == 'valor2')
print('Indice:', indice)  # 1
print('Palavra:', palavra)  #  {'palavra': 'valor2'}
    
14.06.2018 / 23:38
0

The same value may be contained in several elements of your list of dictionaries. One solution would be to build a list containing the index of each element / dictionary in which the value was found, see:

palavra1 = {'palavra': 'valor1'}
palavra2 = {'palavra': 'valor2'}
palavra3 = {'palavra': 'valor3'}
palavra4 = {'palavra': 'valor1'}

palavras = [ palavra1, palavra2, palavra3, palavra4 ]

idxlst = [i for i, d in enumerate(palavras) if d["palavra"] == "valor1"]

print( idxlst )

Output:

[0, 3]
    
15.06.2018 / 02:43