How do I tell dict() in Python 2 to use unicode instead of byte string?

时间:2022-12-28 07:10:51

Here is an example:

这是一个例子:

d = dict(a = 2)
print d
{'a': 2}

How can I tell dict() constructor to use Unicode instead without writing the string literal expliclity like u'a'? I am loading a dictionary from a json module which defaults to use unicode. I want to make use of unicode from now on.

我怎么能告诉dict()构造函数使用Unicode而不用像u'a'那样编写字符串文字明确性?我从json模块加载字典,默认使用unicode。我想从现在开始使用unicode。

2 个解决方案

#1


7  

To get a dict with Unicode keys, use Unicode strings when constructing the dict:

要获取带有Unicode密钥的dict,请在构造dict时使用Unicode字符串:

>>> d = {u'a': 2}
>>> d
{u'a': 2}

Dicts created from keyword arguments always have string keys. If you want those to be Unicode (as well as all other strings), switch to Python 3.

从关键字参数创建的Dicts始终具有字符串键。如果您希望这些是Unicode(以及所有其他字符串),请切换到Python 3。

#2


5  

Keyword arguments in 2.x can only use ASCII characters, which means bytestrings. Either use a dict literal, or use one of the constructors that allows specifying the full type.

2.x中的关键字参数只能使用ASCII字符,这意味着字节串。使用dict文字,或使用允许指定完整类型的构造函数之一。

>>> dict(((u'a', 2),))
{u'a': 2}

#1


7  

To get a dict with Unicode keys, use Unicode strings when constructing the dict:

要获取带有Unicode密钥的dict,请在构造dict时使用Unicode字符串:

>>> d = {u'a': 2}
>>> d
{u'a': 2}

Dicts created from keyword arguments always have string keys. If you want those to be Unicode (as well as all other strings), switch to Python 3.

从关键字参数创建的Dicts始终具有字符串键。如果您希望这些是Unicode(以及所有其他字符串),请切换到Python 3。

#2


5  

Keyword arguments in 2.x can only use ASCII characters, which means bytestrings. Either use a dict literal, or use one of the constructors that allows specifying the full type.

2.x中的关键字参数只能使用ASCII字符,这意味着字节串。使用dict文字,或使用允许指定完整类型的构造函数之一。

>>> dict(((u'a', 2),))
{u'a': 2}