python - 列表到Python中的字典转换

标签 python list dictionary

我有一个包含以下名称的列表

d=[['Srini'], ['Rahul'], ['Mano'], ['Rahul'], ['Srini'], ['Mano], ['Srini'], ['Rahul']]

我正在使用下面的代码将列表转换为字典,该字典应将名称保存为键,将名称的计数保存为值。

dic={}
for words in d:
    dic[words]= dic.get(words,0)+1
print(dic)

ERROR: TypeError Traceback (most recent call last) in () 1 dic={} 2 for words in d: ----> 3 dic[words]= dic.get(words,0)+1 4 print(dic)

TypeError: unhashable type: 'list'

最佳答案

列表是不可散列的。但是,您可以假设每个子列表都有一个元素并引用它:

dic={}
for words in d:
    dic[words[0]]= dic.get(words[0], 0) + 1
print(dic)

请注意,顺便说一句,python 的 Counter 已经具有非常相似的功能:

from collections import Counter
print(Counter((i[0] for i in d)))

关于python - 列表到Python中的字典转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49210484/

相关文章:

python - OS X 上 $PATH 异常

python - 为什么我的 pyglet 程序在渲染 128 个粒子时速度很慢?

python - 转换并加入多个嵌套的列表列表

python - 如何在Python列表中查找某些值的特定索引

python字典检查是否存在给定键以外的任何键

python - 如何通过指定值范围从字典中提取数据?

python - 删除列表中的空白行和多余空间 - python

java - php以JSON形式回显多维数组

python - 生成满足特定条件的 7 个字母单词列表 - Python

python - 使用 python 将文件读取为 json 的替代方法