如何从字符串形成字典?

时间:2015-03-26 10:38:22

标签: python for-loop dictionary

word = 'stacks' 
word_dict = {} # to form new dictionary formed from
for letter in word:
    word_dict[letter] += 1
print word_dict

我想从字符串创建一个新字典,跟踪来自word的字母数。所以我想要的是:

> word_dict = {'s':2, 't':1, 'a':1, 'c':1, 'k':1}

但我无法弄清楚如何做到这一点。我使用当前代码获得KeyError

2 个答案:

答案 0 :(得分:8)

改为使用collections.Counter() class

from collections import Counter

word_dict = Counter(word)

Counter完全相同;计算word中每个字母的出现次数。

在您的特定情况下,您没有先检查密钥是否已存在,或者如果不存在则提供默认密钥。您可以使用dict.get()来执行此操作:

word = 'stacks' 
word_dict = {} # to form new dictionary formed from
for letter in word:
    word_dict[letter] = word_dict.get(letter, 0) + 1
print word_dict

或单独使用dict.setdefault()在增量前显式设置默认值:

word = 'stacks' 
word_dict = {} # to form new dictionary formed from
for letter in word:
    word_dict.setdefault(letter, 0)
    word_dict[letter] += 1
print word_dict

或自己测试密钥:

word = 'stacks' 
word_dict = {} # to form new dictionary formed from
for letter in word:
    if letter not in word_dict:
        word_dict[letter] = 0
    word_dict[letter] += 1
print word_dict

按效率降序排列。

如果密钥尚不存在,您可以使用collections.defaultdict() object自动插入0

from collections import defaultdict

word_dict = defaultdict(int)
for letter in word:
    word_dict[letter] += 1
print word_dict

这基本上是Counter类所做的,但该类型增加了一些其他细节,例如列出最常用的键或组合计数器。

演示:

>>> from collections import defaultdict, Counter
>>> word = 'stacks' 
>>> word_dict = {} # to form new dictionary formed from
>>> for letter in word:
...     word_dict[letter] = word_dict.get(letter, 0) + 1
... 
>>> word_dict
{'a': 1, 'c': 1, 's': 2, 't': 1, 'k': 1}
>>> word_dict = defaultdict(int)
>>> for letter in word:
...     word_dict[letter] += 1
... 
>>> word_dict
defaultdict(<type 'int'>, {'a': 1, 'c': 1, 's': 2, 't': 1, 'k': 1})
>>> Counter(word)
Counter({'s': 2, 'a': 1, 'c': 1, 't': 1, 'k': 1})

答案 1 :(得分:1)

试试这个

from collections import Counter
>>>Counter(word)
Counter({'s': 2, 'a': 1, 'c': 1, 't': 1, 'k': 1})