我有一个代码,可以计算几个度量标准,这些度量标准存储为字典的3维字典。我想将此字典打印到一个csv文件中-但是还没有找到一个好的方法。
计算完字典中的所有元素后,我想将其打印到文件(其中不同的periods
是文件的标题,而keys
和指标a, b, and c
应该是列-列键和列指标)。
有没有简单的方法可以将此打印到文件? (我的第一次尝试是熊猫,但这没有用)
谢谢
from collections import defaultdict
import pandas as pd
import os
import random
# 3 dimensional dictionary that stores integers
output_dict = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
# Array of periods
periods = range(0, 2)
# relevant keys
keys = ["key1", "key2"]
# Iterate over all periods
for period in periods:
# Iterate over all relevant keys
for key in keys:
# Store results for key for each time period for each category ("a", "b", or "c")
output_dict[key][period]["a"] += random.randint(1, 1000)
output_dict[key][period]["b"] += random.randint(1, 1000)
output_dict[key][period]["c"] += random.randint(1, 1000)
# This is the tricky part!!!
# Store results
pd.DataFrame(output_dict).to_csv("output_dict.csv", index=False)
# the dictionary may look as follows:
output_dict = {"key1": {0: {"a": 0.9, "b": 0.2, "c": 0.5}, 1:{"a": 0.91, "b": 0.3, "c": 0.4}},
"key2": {0: {"a": 0.4, "b": 0.33, "c": 0.34}, 1: {"a": 0.21, "b": 0.73, "c": 0.54}}}
最佳答案
您应该为此使用csv
模块,我认为不值得整理数据以使其与pandas
DataFrame构造函数很好地配合使用。注意,我正在将csv写入字符串I / O缓冲区而不是文件中,以便我可以轻松打印结果,但是您可以简单地忽略该内容并仅使用普通的文件对象。
>>> periods = [0, 1]
>>> metrics = ['a', 'b', 'c']
>>> import csv
>>> import io
现在,只需仔细建立行:
>>> with io.StringIO() as f:
... writer = csv.writer(f)
... writer.writerow(['Key','Metric', 0, 1])
... for key in output_dict:
... for metric in metrics:
... row = [key, metric]
... for p in periods:
... row.append(output_dict[key][p][metric])
... writer.writerow(row)
... final = f.getvalue()
...
16
17
18
18
17
16
16
>>> print(final)
Key,Metric,0,1
key2,a,0.4,0.21
key2,b,0.33,0.73
key2,c,0.34,0.54
key1,a,0.9,0.91
key1,b,0.2,0.3
key1,c,0.5,0.4
注意,键将没有任何特定的顺序,因为字典是无序的。如果您提前知道所有键,则可以通过迭代所有键来施加命令,就像我对度量标准和期间所做的那样(您的问题暗示那些键是提前知道的)。此解决方案可以扩展为轻松解决丢失的密钥。
编辑:
您的上一次编辑似乎暗示您将提前知道按键,因此只需执行以下操作:
>>> periods = [0, 1]
>>> keys = ['key1', 'key2']
>>> metrics = ['a', 'b', 'c']
>>> with io.StringIO() as f:
... writer = csv.writer(f)
... writer.writerow(['Key','Metric', 0, 1])
... for key in keys:
... for metric in metrics:
... row = [key, metric]
... for p in periods:
... row.append(output_dict[key][p][metric])
... writer.writerow(row)
... final = f.getvalue()
...
16
17
16
16
17
18
18
>>> print(final)
Key,Metric,0,1
key1,a,0.9,0.91
key1,b,0.2,0.3
key1,c,0.5,0.4
key2,a,0.4,0.21
key2,b,0.33,0.73
key2,c,0.34,0.54
关于python - 将多维字典写入文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42210544/