python中列表中的JSON或CSV
Posted
技术标签:
【中文标题】python中列表中的JSON或CSV【英文标题】:JSON or CSV from list in python 【发布时间】:2022-01-07 17:15:06 【问题描述】:所以我有一个将我的类别树转换为列表的代码,我想将其转换为 CSV/json。列表中的每个项目都可以有多个 id,如下所示。
def paths(tree):
tree_name = next(iter(tree.keys()))
if tree_name == 'children':
for child in tree['children']:
for descendant in paths(child):
yield (tree['id'],) + descendant
else:
yield (tree['id'],)
pprint.pprint(list(paths(tree)))
输出
[(461123, 1010022280, 10222044, 2222871,2222890),
(461123, 129893, 119894, 1110100250),
(461123, 98943, 944894, 9893445),
(461123, 9844495)]
有什么方法可以改进我的代码,或者有其他代码可以将列表转换为 json 并在输出下方显示?
Output should look like this
"column1": "462312",
"column2": "1010022280",
"column3": "10222044",
"column4": "2222871",
"column5": "2222890"
,
"column1": "461123",
"column2": "129893",
"column3": "119894",
"column4": "1110100250"
and so on...
如果 csv 应该是这样的。 ** 最多可达第 10 列
column1 | column2 | column3 | column4 |
---|---|---|---|
461123 | 129893 | 119894 | 1110100250 |
461123 | 129893 | 119894 |
【问题讨论】:
【参考方案1】:以下是将元组列表转换为 dict 列表的代码,您可以将其转换为 json,第二个函数将数据转换为 csv
data = [(461123, 1010022280, 10222044, 2222871,2222890),
(461123, 129893, 119894, 1110100250),
(461123, 98943, 944894, 9893445),
(461123, 9844495)]
def convert_to_list_of_dicts(data):
output_list = []
for i in data:
data_dict =
for count,j in enumerate(i) :
data_dict["column" + str(count+1)] = j
output_list.append(data_dict)
return output_list
# print(convert_to_list_of_dicts(data))
def convert_to_csv(data):
max_column_num = 0
for i in data:
if len(i) > max_column_num:
max_column_num = len(i)
columns = ["column" + str(i+1) for i in range(max_column_num)]
newdata = [tuple(columns)]
for tup in data:
newdata.append(tup)
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(newdata)
# convert_to_csv(data)
【讨论】:
以上是关于python中列表中的JSON或CSV的主要内容,如果未能解决你的问题,请参考以下文章