我创建了一个Python脚本,用于从API中获取数据,该API在&text; / csv'中返回。格式。我想要做的是使用CSV文件中的标题创建字典字典,或者可能是列表字典,具体取决于更有效。
输出是一个长字符串,我将其分解为一个列表,然后是一个包含以下代码的字典(我已对此进行了清理):
{0: '"Header1,Header2,Header3,Header4',
1: 'R1C1,R1C2,R1C3,R1C4'
2: 'R2C1,R2C2,R2C3,R2C4"'}
打印dict_results看起来像这样:
{0: {"Header1":"R1C1", "Header2":"R1C2", "Header3":"R1C3", "Header4":"R1C4"}
1: {"Header1":"R2C1", "Header2":"R2C2", "Header3":"R2C3", "Header4":"R2C4"}
2: {"Header1":"R3C1", "Header2":"R3C2", "Header3":"R3C3", "Header4":"R3C4"}}
所以我想做的就是得到一些看起来像这样的东西:
while
我还注意到,从results_json_data创建的第一个字符串有一个"在开始和"最后,我可能需要剥离,以使我看起来像我想要的一切。希望有人能指出我正确的方向;我是编程/ Python的新手。
答案 0 :(得分:2)
特别关注csv
模块和DictReader
课程。如果可能,您应该使用已建立的库来处理csv数据,而不是自己动手:
> import csv
# first param must be an iterable producing strings (the lines of your csv data)
# this tyically is a file-like object, but can be a plain list
> reader = csv.DictReader(list_results_split, delimiter=',')
> reader.fieldnames
["Header1", "Header2", "Header3"]
> lst = list(reader)
[{"Header1":"R1C1", "Header2":"R1C2", "Header3":"R1C3", "Header4":"R1C4"},
{"Header1":"R2C1", "Header2":"R2C2", "Header3":"R2C3", "Header4":"R2C4"},
{"Header1":"R3C1", "Header2":"R3C2", "Header3":"R3C3", "Header4":"R3C4"}]
# And
> dict(enumerate(lst))
{0: {"Header1":"R1C1", "Header2":"R1C2", "Header3":"R1C3", "Header4":"R1C4"}
1: {"Header1":"R2C1", "Header2":"R2C2", "Header3":"R2C3", "Header4":"R2C4"}
2: {"Header1":"R3C1", "Header2":"R3C2", "Header3":"R3C3", "Header4":"R3C4"}}
查看原始字符串和输出,您应该考虑在处理之前剥离"
:
results_json_data = results_json_data.strip('"')
答案 1 :(得分:1)
因为(半)单行很有趣:
string = """Header1,Header2,Header3,Header4
R1C1,R1C2,R1C3,R1C4
R2C1,R2C2,R2C3,R2C4"""
string = string.split()
headers, data = string[0].split(","), string[1:]
d = {j:{headers[i]:data[j].split(",")[i] for i in range(len(headers))} for j in range(len(data))}
输出
{0: {'Header2': 'R1C2', 'Header3': 'R1C3', 'Header1': 'R1C1', 'Header4': 'R1C4'},
1: {'Header2': 'R2C2', 'Header3': 'R2C3', 'Header1': 'R2C1', 'Header4': 'R2C4'}}