python 字典到 csv,其中每个键在单独的行中,值在单独的列中

python dictionary to csv where each key is in seperate row and value in separate columns

我在尝试将字典输出到 CSV 文件时遇到问题。我有一个字典,其中包含作为键的时间日期和值,以及与这些日期相关的公司,这些日期是字符串格式的。我试着在网站上寻找相同的问题,但这对我的情况没有帮助。我尝试了以下代码并设法在第一行中获取键,在第二列中获取值,但这不是我想要的。

import csv
with open('dict1.csv','w') as f:
    w = csv.writer(f,delimiter=',')
    for key,values in sorted(a.items()):
        w.writerow([key,values])

但这给了我一个格式如下的 CSV 文件:

2009/01/02  ['AA' 'BB' 'AAPL'] etc
2009/01/03  ['AA' 'CC' 'DD' 'FF']

因此我只有两列。但我想要:

2009/01/02  'AA' 'BB' 'AAPL'
2009/01/02  'AA' 'CC' 'DD'  'FF'

第一行分 4 列,第二行分 5 列。
我什至试过

for dates in sorted(a):
    w.writerow([date] + my_dict[date] )

但这给了我一个错误,说 + 'timestamp' 和 'str' 不受支持的操作数类型。

如有任何帮助,我们将不胜感激。谢谢

您可能需要这样输入:

for key,values in sorted(a.items()):
    w.writerow(str(key) + "," + ","join(values))

",".join(values) 会将值列表拆分为以逗号分隔的字符串。我假设你想要逗号分隔你的列,因为你正在编写一个 csv 文件,即使在你的示例中,列是由制表符分隔的。

此行将键(日期)放入键变量中,并将值作为 list 放入值中。所以值确实会包含类似 ['AA' 'BB' 'AAPL'].

的内容
for key,values in sorted(a.items()):

接下来,您要告诉 writerow "write a row with two elements: the first is the key, the second is whatever is in values"(这是一个列表,所以它只是转换为字符串表示形式并像那样输出)。

    w.writerow([key,values])

所以 [key, values] 看起来像这样:

[2009/01/02, ['AA','BB','AAPL']]
 ^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^
 the key     this whole thing
             is the single value

我认为您想要的是创建一个包含键和字符串的列表,而不是包含键和字符串列表的列表。您可以使用额外的值扩展列表,如下所示:

    the_row = [key]  # Create the initial row with just key
    the_row.extend(values)  # Add the values, one by one, to the row
    w.writerow(the_row)  # Write the full row

list.extend(L) 做:通过附加给定列表中的所有项目来扩展列表。

对不起,如果我读错了,但是你在使用 python pandas 吗?

" I have a Dictionary that contains as keys pandas time dates and as values, >companies pertaining to those dates which are in string format."

在那种情况下,类似的方法可能会起作用

import pandas as pd
df = pd.DataFrame(mydict)
df = df.transpose()
df.to_csv('dict1.csv',encoding='utf-8')

to_csv 方法默认使用“,”作为分隔符,您可以根据需要进行更改。