这不能在Python中完成。您将收到TypeError
。原因是字典键必须是一个可排列的对象,其中一个dict
不是。作为一个例子,试试这个:
>>> d0 = {'foo': 'bar',}
>>> assert d0 == {'foo': 'bar'}
>>> d1 = {d0: 'baz',}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> hash(d0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>>
之所以dict
s为没有哈希的是,他们可变对象。这意味着(大体上)他们可以改变(尽管比这更微妙一点,引用Python文档)。 IIRC,在引擎盖下,Python使用散列表来实现字典键,所以如果一个对象不可散列,它就不能用作键。有关可变和不可变对象的更多信息,请参阅Python文档的Data Model部分。
正如其他人所说,你应该使用不可变对象,比如一个元组或namedtuple,为您的关键:
>>> from collections import namedtuple
>>> colors = 'red blue'.split(' ')
>>> shapes = 'circle square'.split(' ')
>>> Figure = namedtuple('Figure', ('color', 'shape'))
>>> my_dict = {Figure(color, shape): {'data': [{}, {}, {}, {},]}
... for color in colors for shape in shapes}
>>> assert my_dict == {Figure(color='blue', shape='circle'): {'data': [{}, {}, {}, {}]}, Figure(color='blue', shape='square'): {'data': [{}, {}, {}, {}]}, Figure(color='red', shape='circle'): {'data': [{}, {}, {}, {}]}, Figure(color='red',shape='square'): {'data': [{}, {}, {}, {}]}}
>>> assert my_dict[('blue', 'circle')] == {'data': [{}, {}, {}, {}]}
>>>
JSON允许在http://stardict.sourceforge.net/Dictionaries.php下载唯一字符串键。 – warvariuc
而且这将工作的唯一方法是如果你创建了自己的继承内置字典类型并实现自己的__hash__函数的类,但是反过来又会导致我想要的字符串,所以只需迭代字典和如果关键对象是字典将其转换为字符串对象。然后,您可以在JavaScript中循环遍历它,并通过将另一个循环加载到解码器中来将该键(字符串)转换为字典。两步转换或在用户定义的类字典中实现'__hash__'。 – Torxed