set as dictionary key

∥☆過路亽.° 提交于 2021-02-11 01:53:05

问题


I ran the below line of code in Python but got an error titled "TypeError: unhashable type: 'set' ". I want to turn that key to a list. How can I solve this error?

dictionary = {
    'a' : [[1,2,3],[4,5,6],[7,8,9]],
    'b' : 2,
    {100} : 3
}
print(dictionary['a'][1][2])

回答1:


keys of a dictionary must be hashable (or better: immutable). set objects are mutable (like lists)

you could use a frozenset instead

dictionary = {
    'a' : [[1,2,3],[4,5,6],[7,8,9]],
    'b' : 2,
    frozenset({100}) : 3
}

A frozenset is a set that is immutable. It's a builtin type. Now you can get the value even by passing a frozenset made of lists/tuples with duplicate entries/any order in the list and it still finds the value

>>> dictionary[frozenset((100,100))]
3



回答2:


You can not have set as a dict key. Keys must be hashable objects (you may interpret it as immutable). So you can use tuple instead:

dictionary = {'a': [[1,2,3],[4,5,6],[7,8,9]], 'b': 2, (100,): 3}


来源:https://stackoverflow.com/questions/59933892/set-as-dictionary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!