Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 796
CppLearner Avatar asked Dec 03 '13 17:12

CppLearner


2 Answers

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

>>> 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.

like image 125
user4815162342 Avatar answered Oct 31 '22 19:10

user4815162342


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.

>>> dict(((u'a', 2),))
{u'a': 2}
like image 38
Ignacio Vazquez-Abrams Avatar answered Oct 31 '22 18:10

Ignacio Vazquez-Abrams