【问题标题】:How to create a new dictionary whose keys are those from another dictionary? unhashable type error如何创建一个新字典,其键来自另一个字典?不可散列的类型错误
【发布时间】:2018-11-19 02:37:54
【问题描述】:

我需要制作一个新字典,它使用与第一个相同的键,而原始值已被平均。到目前为止,这些值并没有给我带来麻烦,但我不知道如何解决“不可散列类型”错误。我应该提到原始字典使用元组作为它的键和值。

studentPerf = 
{('Jeffery','male','junior'):[0.81,0.75,0.74,0.8],
('Able','male','senior'):[0.87,0.79,0.81,0.81],
('Don','male','junior'):[0.82,0.77,0.8,0.8],
('Will','male','senior'):[0.86,0.78,0.77,0.78]}

dictAvgGrade = {studentPerf.keys():[(sum(grade)/4) for grade in studentPerf.values()]}

【问题讨论】:

    标签: python dictionary tuples


    【解决方案1】:

    您的字典理解不正确。试试这个:

    dictAvgGrade = {key: sum(grades)/len(grades) for key, grades in studentPerf.items()}
    

    您遇到错误的部分原因是尝试使用 studentPerf.keys() 作为字典键,因为它要么是 Python 3 中的迭代器,要么是 Python 3 中的列表——两者都不是可散列的。

    【讨论】:

      【解决方案2】:

      根据this

      可散列

      如果一个对象的哈希值在其生命周期内永远不会改变(它需要一个 hash() 方法),并且可以与其他对象进行比较(它需要一个 eq() 方法)。比较相等的可散列对象必须具有相同的散列值。

      哈希性使对象可用作字典键和集合成员,因为这些数据结构在内部使用哈希值。

      所有 Python 的不可变内置对象都是可散列的,而没有可变容器(例如列表或字典)是可散列的。默认情况下,作为用户定义类实例的对象是可散列的;它们都比较不相等,它们的hash值就是它们的id()。

      这意味着 key 不能是一个列表,这是 dict.keys() 返回的。所以你可以使用字典理解,就像我之前提到的一些。应该是这样的。

          dictAvgGrade = {key: sum(values)/len(values) for key,values in studentPerf.items()}
      

      这应该可以解决问题。希望它有所帮助:)

      【讨论】:

      • 哇,第一个评论并获得批准 :) 谢谢 :)
      【解决方案3】:

      使用dictionary comprehension

      print({k:sum(v)/len(v) for k,v in studentPerf.items()})
      

      输出:

      {('Jeffery', 'male', 'junior'): 0.7749999999999999, ('Able', 'male', 'senior'): 0.8200000000000001, ('Don', 'male', 'junior'): 0.7974999999999999, ('Will', 'male', 'senior'): 0.7975000000000001}
      

      【讨论】:

        【解决方案4】:

        你得到一个不可散列的类型错误,因为当你执行 .keys() 时,结果看起来像

        {dict_keys([('Jeffery', 'male', 'junior'), ('Able', 'male', 'senior'), ('Don', 'male', 'junior'), ('Will', 'male', 'senior')]): SOMETHING}
        

        Python 不能这样做,因为 dict_keys 不是可接受的键类型。在您的代码中还需要注意的另一件事是,您尝试分别执行键和值。字典不保证顺序。即使代码有效。顺序会搞砸的。

        正确的做法是使用以下项目

        {student: sum(student_marks)/4 for student, student_marks in studentPerf.items()}
        

        【讨论】:

          猜你喜欢
          • 2021-07-12
          • 1970-01-01
          • 2022-11-15
          • 2022-07-23
          • 1970-01-01
          • 2021-07-07
          • 2016-10-05
          • 2014-06-17
          • 2021-03-09
          相关资源
          最近更新 更多