TomHere TomHere - 5 months ago 8
Python Question

Python: Save keywords in a list and add another list to the single words in it

I want to have a global variable. In the variable I want to save a list of keywords. And after I want to add to every keyword another list of booleans. My first try was to do it like this:

global variable = {}
for word in wordlist:
variable[word]
for boolean in booleanlist:
variable[word].append(True)


I get an error at "variable[word]" because of an KeyError. This should be the part there I add the word into my list.
So after I want to count all the Trues for each word like:

variable[wordA].count(True)


Thanks for help :)

Answer

To fix the KeyError you can do the following thing:

variable = {}
for word in wordlist:
    variable[word] = []
    for boolean in booleanlist:
        variable[word].append(True)

Note that in this code snippet every keyword has the same list of Booleans, but that's what you have given to us.


edit: removed the global declaration, it was there only because the OP had it.