使用中文在Python中建立字典 [英] Using Chinese to build a dictionary in Python

查看:70
本文介绍了使用中文在Python中建立字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是我第一次来这里,也是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'}

我还尝试在带有汉字的字符串的开头添加"u",甚至是方法".encode('utf-8')",但这些似乎都不起作用.我通常会工作我试图检查所有的首选项,并且阅读了PEP网页以及发布的许多其他问题.这很有趣,它可以与字符串和raw_input方法配合使用,但除此之外...

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

推荐答案

在打印字典时(例如, print(dictionary)),键的 repr 并显示值.

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

相反,请尝试:

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

产量:

Hello --> 你好

这篇关于使用中文在Python中建立字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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