为词典添加for循环

时间:2012-06-13 09:29:17

标签: python list dictionary for-loop python-2.7

我在将循环答案插入列表时遇到问题:

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

有了这个我得到像

这样的字数字典
{'red':4,'blue':3}
{'yellow':2,'white':1}

是否有可能以某种方式将这些答案添加到像

这样的列表中
 [{'red':4,'blue':3},{'yellow':2,'white':1}]

基本上我从for循环中得到5个字典,是否可以将所有这些字典放入一个列表中,而无需更改每个字典。每当我尝试将它们放入一个列表时,它就会给我一些类似的东西:

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

http://pastebin.com/60rvcYhb

这是我的程序的副本,没有我用来编码的文本文件,基本上books.txt只包含来自5位作者的5个不同的txt文件,并且即时通讯中我有所有单词的计数在单独的词典中,我想添加到一个列表,如:

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

1 个答案:

答案 0 :(得分:6)

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)

或简单地说:

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

示例:

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}]