使用 python 字典中的 unicode 键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24532229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Working with unicode keys in a python dictionary
提问by drumboots
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.
我正在使用 Python 2.7.x 学习 Twitter API。我已经保存了一些随机推文,我正在尝试处理它们。每条推文都被转换为带有 json.loads 的字典,并且所有的字典都是列表的一部分。
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:
给定一条推文,我希望能够从字典中提取某些字段。键都是 unicode 字符串。如果我在循环中遍历键,则打印值没有问题:
for i in tweet.keys():
print i, tweet[i]
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.
所以上面的循环工作正常,但我没有弄清楚如何手动指定密钥。“u'text'”是实际推文内容(用户的实际帖子)的键。如果我尝试打印 tweet['text'],我会收到 KeyError。我天真地尝试 tweet[u'text'] ,但也因 KeyError 失败了。
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.
我想我很好奇循环在执行 tweet.keys() 时所做的事情与我手动指定键时所做的事情之间的区别。请注意,如果我在上面的循环中打印 i 的值,则会打印键名,但没有 unicode 包装。当键是“u'text'”时,i 的值就是“text”,或者至少这是打印到终端的内容。
采纳答案by Martijn Pieters
Python 2 handles translation between str
and unicode
keys transparently for you, provided the text can be encoded to ASCII:
Python 2为您透明地处理str
和unicode
键之间的转换,前提是文本可以编码为 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'
This means that if you get a KeyError
for tweet['text']
, then that dictionary has no such key.
这意味着如果你得到一个KeyError
for tweet['text']
,那么那个字典就没有这样的键。
回答by Andrew Tikhonov
Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {u'text': u'Foo'}
>>> print "d:{text}".format(**d)
d:Foo