【问题标题】:List to Dictionary conversion in PythonPython中的列表到字典转换
【发布时间】:2018-03-10 15:01:12
【问题描述】:

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

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

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

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

错误: TypeError Traceback(最近一次调用 最后)在() 1 迪克={} 2 对于 d 中的单词: ----> 3 dic[words]= dic.get(words,0)+1 4 打印(dic)

TypeError: unhashable type: 'list'

【问题讨论】:

  • 您不能使用列表作为字典的键。

标签: python list dictionary


【解决方案1】:

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

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)))

【讨论】:

    【解决方案2】:

    你可以试试这个:

    dic = {}
    for i in range(len(d)):
        if d[i] in dic:
            dic[d[i]] += 1
        else:
            dic[d[i]] = 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-10
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 2014-07-28
      • 1970-01-01
      相关资源
      最近更新 更多