如何创建一个新的字典,它的键是来自另一个字典的键?不易损坏的类型

2024-09-25 00:28:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()]}

Tags: 字典type错误ablewillmale平均值元组
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}

根据this

hashable

An object is hashable if it has a hash value which never changes during its lifetime (it needs a hash() method), and can be compared to other objects (it needs an eq() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id().

这意味着键不能是列表,这就是听写键()返回。所以你可以使用字典理解,就像我之前提到的。应该是这样的。你知道吗

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

这样就可以了。希望有帮助:)

你的词典理解不正确。试试这个:

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

出现错误的部分原因是试图使用studentPerf.keys()作为字典键,因为它要么是python3中的迭代器,要么是python3中的and list,这两者都不可散列。你知道吗

相关问题 更多 >