這是一個 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 來制作它......
uj5u.com熱心網友回復:
如果同一年的同一產品沒有不同的值,那么您可以創建一個結構,例如-
{
"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”的整數值
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/365295.html
