In Python, a dictionary (dict) cannot be used as a key in another dictionary. This is because dictionary keys must be immutable (unchangeable) and hashable (capable of producing a unique hash value). Since dictionaries themselves are mutable (modifiable), they cannot serve as keys.
If you need to use the contents of a dictionary as a key, convert it to an immutable type:
1. Tuples: Convert the dictionary to a tuple of sorted key-value pairs (if order matters, sort the items first):
python
my_dict = {'a': 1, 'b': 2}
key = tuple(sorted(my_dict.items)) ('a', 1), ('b', 2)
parent_dict = {key: 'value'}
2. Frozenset: If the order of items doesn’t matter (e.g., for unordered key comparisons):
python
key = frozenset(my_dict.items)
3. String Serialization: Serialize the dictionary to a string (e.g., JSON):
python
import json
key = json.dumps(my_dict, sort_keys=True) '{"a": 1, "b": 2}'
python
This will raise a TypeError:
invalid_dict = {{'a': 1}: 'value'} TypeError: unhashable type: 'dict'
In summary, while a dictionary itself cannot be a key, its contents can be transformed into an immutable representation for use as a key.
版权声明: 知妳网保留所有权利,部分内容为网络收集,如有侵权,请联系QQ793061840删除,添加请注明来意。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态
