5

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.

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes. But if I want to use a instead of using a string literal explicit?
@CppLearner: You cannot with dict(). That's using Python keywords, which are always (byte) strings.
Ah thanks. Just saw the edit and Ignacio's answer. So only Python 3 is capable of doing this by default using keyword argument in the constructor.
@CppLearner Yes, that's what the answer says.
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.

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

2 Comments

Right at the moment I don't have a 3.x handy with me. So in 3.x using keyword argument the default is unicode or not?
@CppLearner: In 3.x, Unicode is the default type for strings period, and identifiers can use any Unicode letter followed by any number of Unicode letters or numbers. 3>> dict(a=2, あ=3) {'あ': 3, 'a': 2}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.