【问题标题】:Writing multiple dictionaries with multiple values in csv file [closed]在csv文件中编写具有多个值的多个字典[关闭]
【发布时间】:2018-09-12 16:30:42
【问题描述】:

我有多个 python 字典,每个字典都有多个值。我想把它们写在 csv 文件中。字典是这样的:

dict1='198': Counter({'65': 9.561,
                      '92': 7.845,
                      '22': 5.994}),

dict2={'613': {},
       '201': {'5351': ['-'],
                  '7': ['+'],
                 '16': ['+'],
                 '43': ['*'],
                 '41': ['*'],
                 '9026': ['+']}}

dict3={'200': [('*',
                'https://m.instantmess.com//stream.php?story_id=2137751112'),
                ('+', '-'),
                ('*',
                 'https://m.instantmess.com//stream.php?story_id=213655363'),
                ('*',
                 'https://m.instantmess.com//stream.php?story_id=2133332333'),
                )]

需要输出格式:

1842    ('*', 'https://m.instantmess.com//stream.php?id=1443556433')  88  + 0.97

dict3 中的第一个值将充当主键。
如何将它们添加到单个 csv 文件中。 我已经尝试过这些答案:
Write Python dictionary with multiple values to CSV
Writing multiple Python dictionaries to csv file

但我的情况是具有多个值的多个字典。 如何解决?

【问题讨论】:

  • 你能举例说明你的预期输出吗?
  • 您的dict2 缺少花括号。
  • 还有Counter是什么?
  • 我只是从控制台粘贴所有值,计数器是集合库中的计数器字典,缺少大括号一定是无意留下的
  • 另外,就像格式问题一样:如果您使用四个空格缩进代码,则不再需要 ` 字符。它只是把事情搞砸了。

标签: python python-3.x csv dictionary


【解决方案1】:

您可以尝试制作一个字典列表,然后从列表中制作一个 pandas DataFrame,然后使用 DataFrame 的 .to_csv() 方法。像这样的:

import pandas as pd
my_list = [dict1, dict2, dict3]
df = pd.DataFrame(my_list)
df.to_csv('path to file')

【讨论】:

  • 我试过了,但它不是我需要的格式,它只是一个大列表。让我添加输出格式,我想要
猜你喜欢
  • 2015-07-25
  • 2017-12-12
  • 2018-10-08
  • 2019-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-08
  • 2021-06-15
相关资源
最近更新 更多