如何在python中从数组创建Dict?

How to create Dict from array in python?

本问题已经有最佳答案,请猛点这里访问。

从这个数组

1
a=[apple , lemon , apple , apple , lemon]

我想创建这样的词典

1
my_dictionary = {'apple':3 , 'lemon':2}


使用collections.Counter

1
2
3
4
>>> from collections import counter
>>> a=['apple' , 'lemon' , 'apple' , 'apple' , 'lemon']
>>> Counter(a)
Counter({'apple': 3, 'lemon': 2})

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.