访问Python字典

5 投票
4 回答
5208 浏览
提问于 2025-04-16 05:29

我正在写一段代码,这段代码会在推特上搜索关键词,并把结果存储在一个Python字典里:

        base_url = 'http://search.twitter.com/search.json?rpp=100&q=4sq.com/'
        query = '7bOHRP'
        url_string = base_url + query
        logging.info("url string = " + url_string)
        json_text = fetch(url_string)
        json_response = simplejson.loads(json_text.content)                                              
        result = json_response['results']
        print "Contents"
        print result

生成的字典是:

Contents[{
    u 'iso_language_code': u 'en',
    u 'text': u "I'm at Cafe en Seine (40 Dawson Street, Dublin) w/ 2 others. http://4sq.com/7bOHRP",
    u 'created_at': u 'Wed, 06 Oct 2010 23:37:02 +0000',
    u 'profile_image_url': u 'http://a1.twimg.com/profile_images/573130785/twitterProfilePhoto_normal.jpg',
    u 'source': u '<a href="http://foursquare.com" rel="nofollow">foursquare</a>',
    u 'place': {
        u 'type': u 'neighborhood',
        u 'id': u '898cf727ca504e96',
        u 'full_name': u 'Mansion House B, Dublin'
    },
    u 'from_user': u 'pkerssemakers',
    u 'from_user_id': 60241195,
    u 'to_user_id': None,
    u 'geo': None,
    u 'id': 26597357992,
    u 'metadata': {
        u 'result_type': u 'recent'
    }
}]
Status: 200 OK
Content - Type: text / html;charset = utf - 8
Cache - Control: no - cache
Expires: Fri, 01 Jan 1990 00: 00: 00 GMT
Content - Length: 0

我该怎么访问里面的'from_user',还有那个在键和值前面的'u'是什么意思呢?

4 个回答

0

注意,在Python 3.x中,你不需要在字符串前加'u',因为所有的字符串都是unicode对象...

在Python 2.x中也可以做到这一点,只需要在代码的顶部加上

from __future__ import unicode_literals
1

你可以这样访问这个项目:

print Contents['from_user']

字符串前面的'u'表示这个字符串是用Unicode编码的。

11
result[0][u'from_user']

这个 u 前缀表示它是一个 unicode 字符串,而不是普通的 str 字符串。

撰写回答