Python 3:将嵌套字典写入CSV

bmvo0sr5  于 2023-10-13  发布在  Python
关注(0)|答案(1)|浏览(121)

我正在尝试将下面的嵌套字典写入带有头的CSV。

headers = [ 'Location', 'Agent', 'Sales', 'Renewals', 'Leaves']
data   = { 'Location1': {'Bob': { 'Sales' : 2, 'Renewals' : 1, 'Leaves' : 1 }},
           'Location1': {'Jim': { 'Sales' : 1, 'Renewals' : 2, 'Leaves' : 3 }},
           'Location2': {'Tod': { 'Sales' : 1, 'Renewals' : 3, 'Leaves' : 1 }}
        }

我对csv模块不熟悉,我查找的指南似乎已经过时,或者确实可以使用这种嵌套的字典。
我期待以下输出:

Location, Agent, Sales, Renewals, Leaves
Location1, Bob, 2, 1, 1
Location1, Jim, 1, 2, 3
Location2, Tod, 1, 3, 1
2ic8powd

2ic8powd1#

您可以在没有csv库的情况下通过手动创建for循环的输出来完成此操作:

# Declare headers and data
headers = ['Location', 'Agent', 'Sales', 'Renewals', 'Leaves']
data = {'Location1': {'Bob': {'Sales': 2, 'Renewals': 1, 'Leaves': 1}},
        'Location1': {'Jim': {'Sales': 1, 'Renewals': 2, 'Leaves': 3}},
        'Location2': {'Tod': {'Sales': 1, 'Renewals': 3, 'Leaves': 1}}
        }

# Add the headers to output
output = ','.join(headers)

# Cycle through data
for key, value in data.items():
    # Declare the items of the row
    row = [key, *value.keys(), *list(value.values())[0].values()]

    # Convert all ints to strings
    row = [str(x) for x in row]

    # Add the data to output
    output += '\n' + ','.join(row)

# Write the output to a file
with open('data.csv', 'w') as file:
    file.write(output)

这将以csv格式将数据写入data.csv

Location,Agent,Sales,Renewals,Leaves
Location1,Bob,2,1,1
Location2,Jim,1,2,3
Location3,Tod,1,3,1

请注意,在data字典中有一个重复的键,这通常不是一个好的做法,但在将其导出到csv文件时可以接受。结果中也没有空格,因为每个值前面都有一个空格。
请使用复选标记接受我的回答,如果它是有帮助的:)

相关问题