Fetch a value within an array of dictionaries

Asked

Viewed 1,389 times

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 given word exists.

Ex:

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

I would like to search whether the word 'yes' is within 'words'. How do I do that?

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

  • Don’t you want to search for the key? Want to search for the value? If yes, the idea is this https://answall.com/a/254612/64969, but the implementation would need some adjustments to fit the list of dictionaries

  • I want to search for the value, because the 'word' key will always be the same... What I want to do at the end of the day is to count the number of positives and negatives in a list of repeating words. So what I really want to do is go through that list. If the word exists, account +1 in positive or negative, depending on its classification in another structure..

2 answers

4

You can use the function filter:

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

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

In addition, you can use a comprehensilist on:

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

Which can be more readable in the code. To set a generator the same way, just replace the brackets with parentheses:

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

See working on Repl.it | Ideone | Github GIST

  • Thank you, Anderson, I used the list comprehension.

1


You can calculate the amount of times the word sim appears inside your list of dictionaries, see only:

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 )

Exit:

1
  • Although Anderson’s response made a lot of sense, I ended up using this one to count how many times it appears. If it is zero, it means that the word does not exist in the list. Thank you

Browser other questions tagged

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