accessing python dictionary – Education Career Blog

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

        base_url = ''
        query = '7bOHRP'
        url_string = base_url + query"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 :

    u 'iso_language_code': u 'en',
    u 'text': u "I'm at Cafe en Seine (40 Dawson Street, Dublin) w/ 2 others.",
    u 'created_at': u 'Wed, 06 Oct 2010 23:37:02 +0000',
    u 'profile_image_url': u '',
    u 'source': u '<a href="" 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?



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


You access the item ala

print Contents'from_user'

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


note that in Python 3.x you don’t need the ‘u’ before the string ’cause all the string are unicode object…

this can be obtained also in Python 2.x, just put at the top of your code

from __future__ import unicode_literals


Since the item returned is a list containing a dictionary you would do:

print Contents0'from_user'

The u is for unicode and you do not need to mention that when you access the data. Python takes care of that.

Since the data returned is in a dictionary itself the final statement would be

print result'Contents'0'from_user'

Leave a Comment