Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing python dictionary

I am writing code that will search twitter for key words and store them in a python dictionary:

        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

The resulting dictionary is :

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

How can I access the 'from_user' and what is the 'u' before the key and value?

like image 582
Stina Avatar asked Oct 14 '10 13:10

Stina


People also ask

Can I access Python dictionary with dot?

Switching to Python, bad news : dot notation is not directly available with the resulting dictionary.

How are values accessed in the dictionary?

The well-known, or I should say the traditional way to access a value in a dictionary is by referring to its key name, inside a square bracket. Notice that when you want to access the value of the key that doesn't exist in the dictionary will result in a KeyError.


2 Answers

result[0][u'from_user']

The u prefix means that it's a unicode instead of a str.

like image 115
Ignacio Vazquez-Abrams Avatar answered Oct 01 '22 17:10

Ignacio Vazquez-Abrams


You access the item ala

print Contents['from_user']

The 'u' in front of the string indicates that the string is uni-code.

like image 31
sizzzzlerz Avatar answered Oct 01 '22 17:10

sizzzzlerz