如何将列表转换为字典?

时间:2017-04-16 16:15:10

标签: python list dictionary

我有这个:

std::array

我希望它和每个键的数量一样:

l = ["a" ,"b" ,"c" ,"d" ,"e" ,"i" ,"i" ,"e"]

2 个答案:

答案 0 :(得分:3)

>>> from collections import Counter
>>> l = ["a", "b", "c", "d", "e", "i", "i", "e"]
>>> Counter(l)
Counter({'e': 2, 'i': 2, 'a': 1, 'c': 1, 'b': 1, 'd': 1})

答案 1 :(得分:0)

.get()方法可用于统计https://www.tutorialspoint.com/python/dictionary_get.htm

下面的行创建了两个变量,列表和空字典:

l, dct = ["a", "b", "c", "d", "e" ,"i" , "i", "e"], {}

然后循环遍历列表中的每个元素并使用.get()检查字典“key”是否存在,如果不存在则会创建它,如果它不存在则设置默认值“ “:

for element in l: dct [element] = dct.get(element, 0)+1

在上述情况下,如果密钥尚不存在,则默认值为0;如果密钥确实存在,则它将+1到字典密钥的现有值[element]

然后打印字典

print (dct)

打印:

{'i': 2, 'd': 1, 'c': 1, 'b': 1, 'a': 1, 'e': 2}