使用 python 字典中的 unicode 键 [英] Working with unicode keys in a python dictionary

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

问题描述

我正在使用 Python 2.7.x 学习 Twitter API.我已经保存了一些随机推文,我正在尝试处理它们.每条推文都被转换成一个带有 json.loads 的字典,所有的字典都是一个列表的一部分.

给定一条推文,我希望能够从字典中提取某些字段.键都是 unicode 字符串.如果我在循环中遍历键,则打印值没有问题:

for i in tweet.keys():打印我,推特[i]

所以上面的循环工作正常,但我没有弄清楚如何手动指定密钥.u'text'"是实际推文内容(用户的实际帖子)的关键.如果我尝试打印 tweet['text'],我会收到 KeyError.我天真地尝试了 tweet[u'text'],但也因 KeyError 失败了.

我想我很好奇循环在执行 tweet.keys() 时所做的事情与我手动指定键时所做的事情之间的区别.请注意,如果我在上面的循环中打印 i 的值,则会打印键名,但没有 unicode 包装.当键是u'text'"时,i 的值就是'text',或者至少是终端打印的内容.

解决方案

Python 2 为您透明地处理 strunicode 键之间的转换,前提是文本可以被编码到 ASCII:

<预><代码>>>>d = {u'text': u'Foo'}>>>d.keys()[u'文本']>>>d 中的文本"真的>>>d 中的文本"真的>>>d['文本']你'福'>>>d[u'文本']你'福'

这意味着,如果您收到 tweet['text']KeyError,则 该字典没有这样的键.>

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.

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]

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.

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

This means that if you get a KeyError for tweet['text'], then that dictionary has no such key.

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

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