Find the index in a value-based array of dictionaries

Asked

Viewed 55 times

0

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

Ex:

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

If I want to find the 'word' index that corresponds to 'value2', how should I proceed?

2 answers

0

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

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 )

Exit:

[0, 3]

0

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

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

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

Knowing this, you can make a loop that iterates under your list and for when you 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'}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.