2017-04-20 250 views
0

我有一個巨大的字典列表從JSON以下列方式附加到列表中。我想從每本字典中訪問「原始」,並將其全部存儲在字典列表或一個巨大的字典中。最終目標是訪問raw中的密鑰並使用pandas將它們轉換爲數據幀列。JSON:遍歷嵌套字典的列表

results = [{ 
    'FirstSentences': None, 
    'PrintableUri': '', 
    'hasHtmlVersion': False, 
    'hasMobileHtmlVersion': False, 
    'isRecommendation': False, 
    'isTopResult': False, 
    'parentResult': None, 
    'percentScore': 100.0, 
    'printableUriHighlights': [], 
    'rankingInfo': None, 
    'rating': 3.0, 
    'raw': {'distance': 1892760.0, 
    'distancekm': 1892.76, 
    'distancemi': 1176.11, 
    'objecttype': 'Account', 
    'objecttypename': 'Account', 
    'plocepp': 'False', 
    'plochpp': 'False', 
    'plocsdp': 'False'}}] 

的代碼,我得到的錯誤是如下:

response = [x['raw'] for x in results] 

File "<ipython-input-90-64993f9dcd67>", line 1, in <module> 
    response = [x['raw'] for x in results] 

TypeError: list indices must be integers, not str 

我尋覓了很多答案,但在這裏無法找到解決我的問題。預先感謝您的幫助。

+0

你的數據有一個錯字.... –

+3

缺少'}'收出第一部字典。最後一行是'plocsdp':'False'}}]'''''''''''''''' – davedwards

+0

對不起,我發佈了一個錯誤,發佈了我現在糾正的問題。該代碼仍然給我同樣的錯誤。 –

回答

0

關鍵是遍歷列表和列表中的每個元素,索引字典鍵'原始'。 一個簡單的方法是迭代列表並訪問字典中的'raw'鍵。

簡單的for循環的方法:

response = [] 
for d in results: 
    response.append(d['raw']) 

列表解析方法

response = [d['raw'] for d in results]