【问题标题】:Write multi dimensional dictionary to file将多维字典写入文件
【发布时间】:2017-07-01 19:43:02
【问题描述】:

我有一个代码可以计算几个指标,这些指标存储为字典的 3 维字典。我想将这本词典打印到 csv 文件中 - 但还没有找到这样做的好方法。

计算完字典中的所有元素后,我想将其打印到文件中(其中不同的 periods 是文件的标题,keys 和指标 a, b, and c 应该是列 - 列键和列指标)。

有没有一种简单的方法可以将其打印到文件中? (我的第一次尝试是 pandas,但这没有用)

谢谢

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}}}

【问题讨论】:

  • 首先,尝试将您的数据转换为具有keyabc 列的 Pandas 数据框。然后,转储到 CSV 应该相当轻松。
  • 如果你能举一个例子说明你的字典是什么样的,你希望 csv 是什么样的
  • @Andreas 可能。实际上,可能有一种简单的方法没有 pandas。如果您可以举一个您正在使用的数据的示例,那么有人可能会回答您的问题
  • @Andreas 是的。 pandas.pydata.org/pandas-docs/stable/generated/… 只需将您的数据转换为必要的 DataFrame。
  • @Andreas 您似乎提供了某种电子表格程序的屏幕截图,这使得实际 csv 的外观有些模糊......

标签: python csv pandas dictionary


【解决方案1】:

您应该为此使用 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

【讨论】:

  • 非常感谢。这正是我一直在寻找的!关于您的帖子的两个问题:a)您如何将final 写入 csv 文件? b)有没有一种简单的方法可以使“writerow”函数动态化(例如无限期)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-20
  • 2023-03-03
  • 2020-08-26
  • 2014-04-12
  • 2016-08-26
相关资源
最近更新 更多