如何将嵌套字典写入CSV文件

时间:2018-03-21 12:00:12

标签: python python-3.x csv dictionary opencsv

我有一本字典

count = {'lt60': {'a': 0, 'b': 0, 'c': 0, 'd': 0}, 'ge60le90': {'a': 4, 'b': 0, 'C': 0, 'd': 0}, 'gt90': {'a': 0, 'b': 1, 'c': 2, 'd': 1} }

我想用这样的CSV格式写这个字典..你可以在这张图片中看到csv file format

我想要的是拍摄来自lt60,ge60le90,gt90的按键,并希望将它们连续写入。就像我选择一个'及其来自所有嵌套字典的值,并在该行中写入其值。

3 个答案:

答案 0 :(得分:2)

您可以使用pandas执行此操作:

import pandas as pd

count = {'lt60': {'a': 0, 'b': 0, 'c': 0, 'd': 0},
         'ge60le90': {'a': 4, 'b': 0, 'c': 0, 'd': 0},
         'gt90': {'a': 0, 'b': 1, 'c': 2, 'd': 1} }

df = pd.DataFrame(count).rename_axis('relation_type').reset_index()

df = df.rename(columns={'ge60le90': 'confidence<90',
                        'gt90': 'confidence>90',
                        'lt60': 'confidence<60'})

df.to_csv('out.csv', index=False)

#   relation_type  confidence<90  confidence>90  confidence<60
# 0             a              4              0              0
# 1             b              0              1              0
# 2             c              0              2              0
# 3             d              0              1              0

答案 1 :(得分:0)

通过迭代你的dict来拉出你的密钥和那些键的值,可以简化这个问题

count = {'lt60': {'a': 0, 'b': 0, 'c': 0, 'd': 0},
         'ge60le90': {'a': 4, 'b': 0, 'c': 0, 'd': 0},
         'gt90': {'a': 0, 'b': 1, 'c': 2, 'd': 1} }

# Create outfile
f = open("C:\\Users\\<USER>\\Desktop\\OUT.csv","w")
# Write first row
f.write(",a,b,c,d\n")

# Iterate through keys
for keys in count:
    print(keys)
    f.write(keys + ",")

    KEYS = count[keys]
# Iterate though values
    for values in KEYS:
        print(KEYS[values])
        f.write(str(KEYS[values]) + ",")
    f.write("\n")
f.close()

答案 2 :(得分:0)

另一种方法是使用AllowOverride All模块。 (请注意,在您的词典中,您有一个大写csv,我在下面的代码中对其进行了更正):

C

请注意,import csv lookup = {'ge60le90': 'confidence<90','gt90': 'confidence>90', 'lt60': 'confidence<60'} count = {'lt60': {'a': 0, 'b': 0, 'c': 0, 'd': 0}, 'ge60le90': {'a': 4, 'b': 0, 'c': 0, 'd': 0}, 'gt90': {'a': 0, 'b': 1, 'c': 2, 'd': 1} } # Getting keys from dictionary that match them with titles below. rowKeys = [k for k in count['lt60'].keys()] titles = [['relation type'] + list(lookup[k] for k in count.keys())] # Getting all row variable values for every title. rows = [[count[k][i] for k in count.keys()] for i in rowKeys] # Concatenating variables and values. fields = [[rowKeys[i]] + rows[i] for i in range(len(rowKeys))] # Concatenating final output to be written to file. result = titles + fields print("Final result to be written: ") for r in result: print(r) # Writing to file. with open("output.csv", "w", newline="") as outFile: writer = csv.writer(outFile, delimiter=';',quotechar='|', quoting=csv.QUOTE_MINIMAL) writer.writerows(result) 分隔符适用于欧洲Windows,可能不适合您。在这种情况下,请改用;