元素计数字典

时间:2015-08-04 21:37:06

标签: python dictionary

我想创建一个包含{x,list.count[x]}的字典。但是,在尝试执行我的代码时,我一直遇到错误:

apple = ['variant', 'variant', 'variant2.0', 'variant 3.0']

pear = {}

for x in apple:
    pear.update({x,apple.count(x)})

错误是cannot convert dictionary update sequence element#0 to a sequence.有任何建议吗?

3 个答案:

答案 0 :(得分:5)

您的字典定义中存在语法错误。 尝试

pear.update({x : apple.count(x)})

答案 1 :(得分:4)

我可以建议collections.Counter

>>> from collections import Counter
>>>
>>> apple = ['variant', 'variant', 'variant2.0', 'variant 3.0']
>>> Counter(apple)
Counter({'variant': 2, 'variant 3.0': 1, 'variant2.0': 1})

如果你之后需要一个简单的词典:

>>> dict(Counter(apple))
{'variant 3.0': 1, 'variant': 2, 'variant2.0': 1}

答案 2 :(得分:1)

apple = ['variant', 'variant', 'variant2.0', 'variant 3.0']
pear = {}
for x in apple:
    pear[x] = pear.get(x, 0) +1
print (pear)

输出:

{'variant 3.0': 1, 'variant': 2, 'variant2.0': 1}