【问题标题】:JSON: iterate over a list of nested dictionariesJSON:遍历嵌套字典列表
【发布时间】:2017-04-20 22:57:25
【问题描述】:

我有一个庞大的字典列表,按以下方式从 JSON 中附加到列表中。我想从每个字典中访问“原始”并将其全部存储在字典列表或一个巨大的字典中。最终目标是访问 raw 中的键并使用 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

我在这里搜索了很多答案,但找不到我的问题的解决方案。非常感谢您提前提供的帮助。

【问题讨论】:

  • 您的数据有错别字......
  • 缺少} 以关闭第一本词典。最后一行为'plocsdp': 'False'}}] 你的response 代码工作正常。
  • 对不起,我在发布问题时打错了字,现在我已经更正了。代码仍然给我同样的错误。

标签: python json list dictionary web-scraping


【解决方案1】:

关键是遍历列表,并为列表中的每个元素,索引字典键'raw'。 一种简单的方法是遍历列表并访问字典中的键“raw”。

简单的for循环方法:

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

列表理解法

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

【讨论】:

    猜你喜欢
    • 2015-12-06
    • 2020-11-13
    • 2012-07-09
    • 2021-03-19
    • 1970-01-01
    • 2017-07-25
    相关资源
    最近更新 更多