如何使用Python将行分隔的数组文件转换为字典?

时间:2015-07-17 13:34:09

标签: json python-2.7

我有一个格式为:

的文件
 ["A","B","C","D","E"]
 ["1",false,null,"3","Hi"]
 ["2",true,"7676","2","Hello"]
 ...
 ["3",true,"222","4","Bye"]

我希望它具有以下格式:

 {"A":"1", "B":false,"C":null,"D":"3","E":"Hi"}
 {"A":"2", "B":true,"C":"7676","D":"2","E":"Hello"}
 ...
 {"A":"3", "B":true,"C":"222","D":"4","E":"Bye"}

3 个答案:

答案 0 :(得分:0)

head = ["A","B","C","D","E"]
l1 = ["1",False,None,"3","Hi"]
l2 = ["2",True,"7676","2","Hello"]
l3 = ["3",True,"222","4","Bye"]
dict1 = {}
dict2 = {}
dict3 = {}
for i in range(len(head)):
    dict1[head[i]] = l1[i]
    dict2[head[i]] = l2[i]
    dict3[head[i]] = l3[i]

答案 1 :(得分:0)

嘿你可以尝试使用

import ast

f = open("s.txt", "r")

text = f.read()

text_list = text.split("\n")
key_list = []
for ind, value_list in enumerate(text_list):
    format_list = []
    if value_list: 
        format_list = ast.literal_eval(value_list)
        if ind == 0:
            key_list = format_list
        else:
            format_dict = {}
            for index, value in enumerate(format_list):
                format_dict[key_list[index]] = format_list[index] 
            print format_dict

此处s.text是一个包含输入的文件

答案 2 :(得分:0)

我提出了以下解决方案。 "文件"是源文件所有数据,如问题中提供的示例

import itertools
import json
with open(file) as f:
      keys = json.loads(f.readline())
      for line in f:
          line = json.loads(line)
          tmp_dict = { k:v for k,v in itertools.izip(keys,line)}
          data.append(json.dumps(tmp_dict))