在python字典中使用unicode键 [英] Working with unicode keys in a python dictionary
问题描述
我正在使用Python 2.7.x了解Twitter API。我保存了一些随机的推文,我正在尝试处理它们。每个tweet都会转换成一个json.loads的字典,所有的字典都是列表的一部分。
I am learning about the Twitter API using Python 2.7.x. I've saved a number of random tweets and I am trying to process them. Each tweet is converted to a dictionary with json.loads and all the dictionaries are part of a list.
给定一个tweet,我想要提取某些字段从字典。键都是unicode字符串。如果我在一个循环中迭代键,我打印的值不用麻烦:
Given a single tweet, I want to be able to extract certain fields from the dictionary. The keys are all unicode strings. If I iterate through the keys in a loop, I have no trouble printing the values:
for i in tweet.keys():
print i, tweet[i]
所以上面的循环很好,但是没有运气弄清楚如何手动指定键。 u'text是实际的推文内容(用户的实际帖子)的关键。如果我尝试打印tweet ['text'],我得到一个KeyError。我真的尝试了tweet [u'text'],但是失败了一个KeyError。
So the loop above works fine, but I have had no luck figuring out how to manually specify key. "u'text'" is the key for the actual tweet content (the user's actual post). If I try to print tweet['text'], I get a KeyError. I naively tried tweet[u'text'] but that fails with a KeyError too.
我想我很好奇循环在做什么之间的差异通过tweet.keys()与我正在手动指定一个键的时候相比。请注意,如果我在上面的循环中打印i的值,则打印键名称,但不包含unicode包装。当键为u'text时,我的值只是'text',或至少是打印到终端的值。
I guess I am curious about the difference between what the loop is doing as it steps through tweet.keys() vs. what I am doing when manually I specifying a key. Note that if I print the value of i in the loop above, the key name is printed, but without the unicode wrapping. When the key is "u'text'", the value of i is just 'text', or at least that is what is printed to the terminal.
推荐答案
Python 2可以透明地处理 str
和 unicode
键之间的翻译,只要文本可以编码为ASCII:
Python 2 handles translation between str
and unicode
keys transparently for you, provided the text can be encoded to ASCII:
>>> d = {u'text': u'Foo'}
>>> d.keys()
[u'text']
>>> 'text' in d
True
>>> u'text' in d
True
>>> d['text']
u'Foo'
>>> d[u'text']
u'Foo'
这意味着如果你得到 KeyError
tweet ['text']
,那么该字典没有这样的键 。
This means that if you get a KeyError
for tweet['text']
, then that dictionary has no such key.
这篇关于在python字典中使用unicode键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!