簡體   English   中英

JSON:遍歷嵌套字典列表

[英]JSON: iterate over a list of nested dictionaries

我有一個龐大的字典列表,以下列方式從JSON附加到列表中。 我想從每個字典訪問“原始”並將其整個存儲在字典列表或一個巨大的字典中。 最終目標是訪問原始數據中的鍵,並使用pandas將其轉換為數據框列。

  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

我在這里搜索了很多答案,但是找不到解決我問題的方法。 非常感謝您的事先幫助。

關鍵是要遍歷列表,並為列表中的每個元素索引字典鍵“ raw”。 一種簡單的方法是遍歷列表並訪問字典中的鍵“原始”。

簡單的for循環方法:

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

列表理解方法

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM