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

How to write nested dictionaries to a CSV file

我有一本字典

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 格式编写这本词典..正如您在这张图片中看到的那样

我想要的是 lt60、ge60le90、gt90 的钥匙图片,并想将它们写成一行。就像我从所有嵌套字典中选择 'a' 及其值并将其值写在该行中。

您可以使用 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

这个问题可以通过迭代你的字典来简化你的键和这些键的值

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()

另一种方法是利用 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,但可能不适用于您。在这种情况下,请改用 ,