循环遍历列表并在python中创建具有字典理解的字典的正确方法是什么?

时间:2016-02-11 22:04:13

标签: python dictionary

testWords是一个包含单词的列表。 setTestWords与集合的列表相同。我想用Dict Comprehension创建一个字典,我将使用单词作为键,计数作为值。我也在使用.count。

示例输出如下:

>>> dictTestWordsCount[:2]
>>> {'hi': 22, 'hello': 99}

这是我正在使用的代码,但它似乎每次都会崩溃我的笔记本。

l = {x: testWords.count(x) for x in setTestwords}

1 个答案:

答案 0 :(得分:2)

不确定导致笔记本电脑崩溃的原因......

In [62]: txt = "the quick red fox jumped over the lazy brown dog"

In [63]: testWords = txt.split()

In [64]: setTestWords = set(testWords)

In [65]: {x:testWords.count(x) for x in setTestWords}
Out[65]:
{'brown': 1,
 'dog': 1,
 'fox': 1,
 'jumped': 1,
 'lazy': 1,
 'over': 1,
 'quick': 1,
 'red': 1,
 'the': 2}

或者更好,使用collection.defaultdict

from collections import defaultdict

d = defaultdict(int)

for word in txt.split():
    d[word]+=1

print(d)
defaultdict(int,
            {'brown': 1,
             'dog': 1,
             'fox': 1,
             'jumped': 1,
             'lazy': 1,
             'over': 1,
             'quick': 1,
             'red': 1,
             'the': 2})