adohertyd
adohertyd

Reputation: 2689

Extracting info from a python dictionary

I have a dictionary object called obj_1 and it's values are shown like this:

{u'd':{u'results': [{u'Desc':u'This is a description...',
                    u'Title':u'This is a title...',
                     u'data': {u'Url': u'www.site.com'}},

                   {u'Desc':u'This is a description...', 
                    u'Title':u'This is a title...',
                     u'data': {u'Url': u'www.site.com'}}]
}}

This is decoded json (decoded using the requests module decoder). How do I extract the u'Title' values and the URL values only? I haven't seen any dictionary types like this in any of the tutorials.

Upvotes: 1

Views: 135

Answers (2)

John La Rooy
John La Rooy

Reputation: 304215

>>> obj_1 = {u'd':{u'results': [{u'Desc':u'This is a description...',
...                     u'Title':u'This is a title...',
...                      u'data': {u'Url': u'www.site.com'}},
... 
...                    {u'Desc':u'This is a description...', 
...                     u'Title':u'This is a title...',
...                      u'data': {u'Url': u'www.site.com'}}]
... }}
>>> [(x[u'Title'], x[u'data'][u'Url']) for x in obj_1[u'd'][u'results']]
[(u'This is a title...', u'www.site.com'), (u'This is a title...', u'www.site.com')]

Upvotes: 1

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

Assuming tyour "obj_1" really looks like this:

obj_1 = {u'd':{u'results': [{u'Desc':u'This is a description...',
                            u'Title':u'This is a title...'},

                            {u'Desc':u'This is a description...', 
                            u'Title':u'This is a title...'}]
        }}

Then its a as simple as:

titles = [d['Title'] for d in obj_1['d']['results']]

Upvotes: 3

Related Questions