如何在python 2.7中重构一系列字典?

时间:2018-04-02 05:55:20

标签: python json python-2.7 dictionary

我已经通过以下过程阅读并构建了一个字典格式的CSV文件:

with open("data.csv") as csvfile: 
    reader = csv.DictReader(csvfile)

我要做的是构建一个for循环来解析这个字典系列,并按系列表示法写入(.stdout)一个新行分隔的(\ n)JSON系列,如下所示:

  {
    "State":"CA",
    "points":[
      ["2015-01-01", 33.5],
      ["2016-01-01", 100.8],
      ["2018-01-01", 10.1]
    ],
    "fields":{
      "Product":"TA",
      "Line":"V1"
    }
  } 

这是csv文件的一个示例:

STATE  DATE    VALUE PRODUCT LINE TRAN
CA    2015-01  33.5   TA      V1   4
CA    2015-05  31.7   TA      V1   4
CA    2016-01  100.8  TA      V1   4
FL    2017-01  93.5   LC      M2   2
FL    2017-03  150.5  LC      M2   4
NY    2013-01  50.4   AB      AB   1
NY    2016-01  70.5   AB      AB   1

这是使用(DictReader)后获得的字典序列的一个例子:

{'STATE': 'CA', 'DATE': '2015-01', 'VALUE': '33.5', 'PRODUCT': 'TA', 'LINE': 'V1', 'TRAN': '4'}
{'STATE': 'CA', 'DATE': '2015-05', 'VALUE': '31.7', 'PRODUCT': 'TA', 'LINE': 'V1', 'TRAN': '4'}

我陷入了for循环中间部分,我无法重新构建这个新的jason序列:

with open("data.csv") as csvfile: 
    reader = csv.DictReader(csvfile)

for row in reader:
        for key in row:


new_jsonsqc = json.dumps(row)
sys.stdout.write(new_jsonsqc + '\n')

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

只需检查按键并相应地追加到new_jsonsqc:

import csv
import json
import sys

with open("data.csv") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        new_jsonsqc = {'points': [], 'fields': {}}
        for key in row:
            if key == 'STATE':
                new_jsonsqc['State'] = row[key]
            if key == 'DATE':
                new_jsonsqc['points'].append(row[key])
            if key == 'VALUE':
                new_jsonsqc['points'].append(row[key])
            if key == 'PRODUCT':
                new_jsonsqc['fields']['Product'] = row[key]
            if key == 'LINE':
                new_jsonsqc['fields']['Line'] = row[key]
        sys.stdout.write(json.dumps(new_jsonsqc) + '\n')