【问题标题】:Create multiple JSON files from CSV by grouping categories通过对类别进行分组从 CSV 创建多个 JSON 文件
【发布时间】:2022-01-01 05:59:27
【问题描述】:

这是一个 CSV 文件:

year,product,price
2021,P01,50
2022,P03,60
2021,P02,30

我正在尝试使用这样的产品列表为每年创建一个 JSON:

{
  "year": "2021",
  "products": {
      "P02": 30,
      "P01": 50
  },
  "processed": "true"
}

这是我的实际代码:

import json

csv = """2021,P01,50
2022,P03,60
2021,P02,30
"""
response = {}

for line in csv.splitlines():
    fields = line.split(",")
    year, product, price = fields[0], fields[1], fields[2:]
    if year not in response:
        response[year] = {}
    response[year][product] = price

print json.dumps(response)

这是我得到的结果:

{
  "2021": {
    "P02": [
      "30"
    ],
    "P01": [
      "50"
    ]
  },
  "2022": {
    "P03": [
      "60"
    ]
  }
}

你能帮我得到我正在等待的结果吗? 我开始认为我应该使用 List 来制作它......

【问题讨论】:

  • 您的代码的哪一部分甚至试图创建“每年的 JSON 文件”?
  • 目前我不创建文件,我只是想按照我的需要进行分组:-/

标签: python json csv


【解决方案1】:

如果同一年的同一产品没有不同的值,那么您可以创建一个结构,如-

{
  "2021": {
    "P0": 50,
    "P1": 30
  },
  "2022": {
    "P0": 60
  }
}

用于创建这样的结构

import json

csv = """2021,P01,50
2022,P03,60
2021,P02,30
"""
response = {}
for line in csv.splitlines():
    fields = line.split(",")
    year, product, price = fields[0], fields[1], fields[2:]
    year_response = response.get(year, {})
    year_response[product] = price
    response[year] = year_response
    
# iterate the dictionary and create your custom response
for year, year_response in response.items():
    file_data = {}
    file_date["year"] = year
    file_data["products"] = year_response
    file_data["processed"] = true
    #TODO: add file_data to file now

如果同一年的同一产品有不同的值,那么您可以简单地使用列表而不是整数值来表示“P0”

【讨论】:

    猜你喜欢
    • 2018-01-12
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 2012-10-14
    • 2019-05-02
    • 2015-11-04
    相关资源
    最近更新 更多