5593404
5593404

Reputation: 1

Adding for loops to dictionaries

I'm having trouble inserting for loop answers into list:

 for i in word_list:
        if i in word_dict:
            word_dict[i] +=1
        else:
            word_dict[i] = 1
print word_dict

with this i get dictionaries of word counts like

{'red':4,'blue':3}
{'yellow':2,'white':1}

is it possible to somehow add these answers to a list like

 [{'red':4,'blue':3},{'yellow':2,'white':1}]

basically i get 5 dictionaries from a for loop, is it possible to put all those dictionaries into one list, without changing each dictionary. Every time i try to put them into one list it just gives me something like:

[{{'red':4,'blue':3}]
[{'yellow':2,'white':1}]
[{etc.}]

http://pastebin.com/60rvcYhb

this is the copy of my program, without the text files im using to code with, basically books.txt just contains 5 different txt files from 5 authors, and im at the point where i have the word counts of all of them in seperate dictionaries which i want to add to one list like:

 [{'red':4,'blue':3},{'yellow':2,'white':1}]

Upvotes: 0

Views: 137

Answers (1)

eumiro
eumiro

Reputation: 212905

word_dict_list = []

for word_list in word_lists:
    word_dict = {}
    for i in word_list:
        if i in word_dict:
            word_dict[i] +=1
        else:
            word_dict[i] = 1
    word_dict_list.append(word_dict)

or simply:

from collections import Counter
word_dict_list = [ dict(Counter(word_list)) for word_list in word_lists]

example:

from collections import Counter
word_lists = [['red', 'red', 'blue'], ['yellow', 'yellow', 'white']]
word_dict_list = [ dict(Counter(word_list)) for word_list in word_lists]
# word_dict_list == [{'blue': 1, 'red': 2}, {'white': 1, 'yellow': 2}]

Upvotes: 6

Related Questions