【问题标题】:Iterating through a dictionary datatype column within an API response遍历 API 响应中的字典数据类型列
【发布时间】:2021-01-20 21:04:42
【问题描述】:

我正在使用 Python 3.9 解析 API 响应,其中一个键(产品)的值是 dict 类型。我需要遍历“产品”键的值。

例子:

[{'id': 78456, 'item': '48-20213', 'product': {'id': 21438274735, 'supplier_part_number': '14109', 'color': 'Green’},'stats': None}] 

这是我迄今为止尝试过的:

df = pd.DataFrame(r.json())

final_df = df[['product']]

如何使用 final_df 来遍历这些值?我正在尝试获取 'supplier_part_number' 的值。

【问题讨论】:

  • 请提供df的样本以及df.info()的结果

标签: python-3.x dataframe dictionary


【解决方案1】:
  import json
  r = [{'id': 78456, 'item': '48-20213', 'product': {'id': 21438274735,'supplier_part_number': '14109', 'color': 'Green'},'stats': None}]
  print(json.dumps(r[0]['product'],indent = 4))

要遍历字典,您可以这样做,因为它是一个嵌套字典,您需要使用“产品”键,如下所示。

  for key, value in r[0]['product'].items():
      print(f"key:{key},value:{value}")

【讨论】:

  • @Alex01 特别是如果它对你有用,accepting an answer 是表达感激之情的方式。
猜你喜欢
  • 1970-01-01
  • 2020-11-30
  • 2019-11-29
  • 1970-01-01
相关资源
最近更新 更多