Find a value within an array of dictionaries

1

Hello, I'm doing the following in python:

I created an array of dictionaries and would like to search within this array if a particular word exists.

Ex:

palavra1 = {'palavra': 'sim', 'positivo': 0}
palavra2 = {'palavra': 'não', positivo: 0}
palavras = [palavra1, palavra2]

I would like to find out if the word 'yes' is within 'words'. How do I do this?

I thought of using the words.index () method, but I also need to use the dictionary get method to check the value of 'word', how would I do it?

    
asked by anonymous 14.06.2018 / 15:14

2 answers

1

You can calculate how many times the word sim appears within your list of dictionaries, see:

palavra1 = {'palavra': 'sim', 'positivo': 0}
palavra2 = {'palavra': 'não', 'positivo': 0}
palavras = [ palavra1, palavra2 ]

n = sum([ d["palavra"] == "sim" for d in palavras ])

print( n )

Or:

palavra1 = {'palavra': 'sim', 'positivo': 0}
palavra2 = {'palavra': 'não', 'positivo': 0}
palavras = [ palavra1, palavra2 ]

n = len([ d for d in palavras if d["palavra"] == "sim" ])

print( n )

Output:

1
    
14.06.2018 / 16:06
4

You can use the filter function:

resultado = filter(lambda termo: termo['palavra'] == 'sim', palavras)

The result will be an iterable (generator) object with all dictionaries that have 'palavra' equal to 'sim' .

In addition, you can use list comprehension :

resultado = [termo for termo in palavras if termo['palavra'] == 'sim']

That can get more readable in code. To define a generator in the same way, simply replace brackets with parentheses:

resultado = (termo for termo in palavras if termo['palavra'] == 'sim')

See working at Repl.it | Ideone | GitHub GIST

    
14.06.2018 / 15:26