2012-07-06 68 views
1

提取信息我有稱爲obj_1字典對象和它的值被示出如下:從Python字典

{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'}}] 
}} 

這是解碼JSON(使用requests模塊解碼器解碼)。我如何提取u'Title'值和URL值?我在任何教程中都沒有看到過這樣的字典。

+5

這看起來並不像一個有效的Python字典。 SO的語法突出顯示你有不一致的地方。 – eumiro 2012-07-06 10:31:46

+1

這是不正確的字典,也不正確的json。 – Stan 2012-07-06 10:39:32

+0

@eumiro抱歉修復了代碼我有一個巨大的輸出,並試圖顯示我搞砸了一點的格式。 – adohertyd 2012-07-06 10:47:08

回答

3

假設tyour 「obj_1」 真的是這樣的:

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...'}] 
     }} 

然後它的一個簡單:

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

感謝布魯諾,請參閱編輯我的問題。我也想要在另一個嵌套部分中的URL。這是'page_urls = [d ['Url'] for obj_1 ['d] ['results'] ['data']' – adohertyd 2012-07-06 10:57:28

1
>>> 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')]