Jeremy Wittkopp
Jeremy Wittkopp

Reputation: 61

Using Chinese to build a dictionary in Python

so this is my first time here, and also I am new to the world of Python. I am studying Chinese also and I wanted to create a program to review Chinese vocabulary using a dictionary. Here is the code that I normally use:

#!/usr/bin/python
# -*- coding:utf-8-*-

dictionary = {"Hello" : "你好"} # Simple example to save time

print(dictionary)

The results I keep getting are something like:

{'hello': '\xe4\xbd\xa0\xe5\xa5\xbd'}

I have also trying adding a "u" to the beginning of the string with the Chinese characters, and even the method ".encode('utf-8'), yet no of these seem to work. I normally work off of the Geany IDE. I have tried to check out all of the preferences, and I have read the PEP web page along with many of the other questions posted. It is funny, it works with strings and the raw_input method, but nothing else...

Upvotes: 5

Views: 3046

Answers (2)

EinLama
EinLama

Reputation: 2406

You can see the characters if you print the values directly:

>>> d = {"Hello" : "你好"}
>>> print d["Hello"]
你好

Upvotes: 1

unutbu
unutbu

Reputation: 880547

When printing a dict, (e.g. print(dictionary)), the reprs of the keys and values are displayed.

Instead, try:

dictionary = {u"Hello" : u"你好"} 
for key,value in dictionary.iteritems():
    print(u'{k} --> {v}'.format(k=key,v=value))

yields:

Hello --> 你好

Upvotes: 8

Related Questions