如何在Python 2中告诉dict()来使用unicode而不是字节串? [英] How do I tell dict() in Python 2 to use unicode instead of byte string?

查看:206
本文介绍了如何在Python 2中告诉dict()来使用unicode而不是字节串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个例子:

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

如何告诉 dict() / code>构造函数来使用Unicode,而不是像 u'a'那样编写字符串文字解释。我从 json 模块中加载一个字典,默认使用unicode。我想从现在起使用unicode。

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.

推荐答案

要获得具有Unicode密钥的dict,在构造时使用Unicode字符串dict:

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

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

从关键字参数创建的Dicts总是有字符串键。如果你想要这些是Unicode(以及所有其他字符串),请切换到Python 3。

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.

这篇关于如何在Python 2中告诉dict()来使用unicode而不是字节串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆