คุณกำลังพยายามที่จะใช้dictเป็นกุญแจสำคัญไปยังอีกหรือในdict setที่ใช้งานไม่ได้เนื่องจากกุญแจต้องถูกแฮช ตามกฎทั่วไปวัตถุที่เปลี่ยนแปลงไม่ได้ (สตริง, จำนวนเต็ม, ลอย, frozensets, tuples ของ immutables) เท่านั้นที่สามารถแฮชได้ (แม้ว่าจะมีข้อยกเว้นก็ตาม) ดังนั้นนี่ใช้ไม่ได้:
>>> dict_key = {"a": "b"}
>>> some_dict[dict_key] = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
ในการใช้ dict เป็นกุญแจคุณจะต้องเปลี่ยนเป็นสิ่งที่อาจถูกแฮชก่อน หาก dict ที่คุณต้องการใช้เป็นคีย์ประกอบด้วยค่าที่ไม่เปลี่ยนรูปแบบเท่านั้นคุณสามารถสร้างการนำเสนอที่แฮชได้เช่นนี้:
>>> key = frozenset(dict_key.items())
ตอนนี้คุณสามารถใช้keyเป็นกุญแจในdictหรือset:
>>> some_dict[key] = True
>>> some_dict
{frozenset([('a', 'b')]): True}
แน่นอนว่าคุณต้องทำแบบฝึกหัดซ้ำทุกครั้งที่คุณต้องการค้นหาบางสิ่งโดยใช้ dict:
>>> some_dict[dict_key] # Doesn't work
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> some_dict[frozenset(dict_key.items())] # Works
True
หากdictคุณต้องการใช้เป็นคีย์มีค่าที่เป็นตัวเองและ / หรือรายการคุณต้อง "หยุด" คีย์ซ้ำในอนาคตซ้ำ ๆ นี่คือจุดเริ่มต้น:
def freeze(d):
if isinstance(d, dict):
return frozenset((key, freeze(value)) for key, value in d.items())
elif isinstance(d, list):
return tuple(freeze(value) for value in d)
return d