在csv文件中编写具有多个值的多个字典

时间:2018-09-12 16:30:42

标签: python python-3.x csv dictionary

我有多个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

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

1 个答案:

答案 0 :(得分:3)

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

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