带unicode键的词典

2024-04-20 12:12:54 发布

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

在Python中,是否可以使用Unicode字符作为字典的键? 我有Unicode的西里尔字母,我用它们作为键。当试图通过键获取值时,我得到以下回溯:

 Traceback (most recent call last):
 File "baseCreator.py", line 66, in <module>
    createStoresTable()
 File "baseCreator.py", line 54, in createStoresTable
    region_id = regions[region]
 KeyError: u'\u041c\u0438\u043d\u0441\u043a/\u041c\u043e\u0441\u043a\u043e\u0432\u0441\u043a\u0438\u0439\xa0'

Tags: inpy字典lineunicode字符regionfile
2条回答

是的,有可能。你得到的错误意味着你使用的密钥不在你的字典中。

要调试,请尝试使用字典;您将看到每个键的repr,它应该显示实际键的外观。

Python 2.x在比较两个键以测试键是否已经存在、访问值或覆盖值时,将这两个键转换为bytestring。一个键可以存储为Unicode,但是如果两个不同的Unicode字符串减少为相同的bytestrings,则不能同时用作键。

In []: d = {'a': 1, u'a': 2}
In []: d
Out[]: {'a': 2}

在某种意义上,您可以使用Unicode键。

Unicode键以Unicode格式保留:

In []: d2 = {u'a': 1}
In []: d2
Out[]: {u'a': 1}

您可以使用任何Unicode字符串bytestring访问该值,该字符串“等于”现有密钥:

In []: d2[u'a']
Out[]: 1

In []: d2['a']
Out[]: 1

使用键或任何“等于”键写入新值的操作将成功并保留现有键:

In []: d2['a'] = 5
In []: d2
Out[]: {u'a': 5}

因为将'a'与现有键进行比较是True,所以将与该现有Unicode键对应的值替换为5。在我给出的初始示例中,文本中为d提供的第二个键u'a'与先前分配的键进行了真实的比较,因此bytestring 'a'被保留为键,但该值被2覆盖。

相关问题 更多 >