简体   繁体   English

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

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

I am having trouble trying to output my dictionary to CSV file. 我在尝试将字典输出到CSV文件时遇到问题。 I have a Dictionary that contains as keys time dates and as values, companies pertaining to those dates which are in string format. 我有一个包含时间日期和值的键的词典,与字符串格式的那些日期有关的公司。 I tried looking through the website for identical question, but it doesn't really help my case. 我尝试通过网站查找相同的问题,但它并没有真正帮助我的情况。 I tried the following code and managed to get the key in first row, values in second column but thats not what i want. 我尝试了以下代码并设法获得第一行中的键,第二列中的值,但这不是我想要的。

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])

But this gives me a CSV file in following format: 但是这给了我一个以下格式的CSV文件:

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

Hence I only have two columns. 因此我只有两列。 But I want: 但我想要:

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

in 4 separate columns for first row and 5 for the second row respectively. 在第一行的4个单独列中,第二行分别为5列。
I even tried 我甚至试过了

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

But this gives me error saying unsupported operand types for + 'timestamp' and 'str'. 但是这给了我错误说+'timestamp'和'str'的不支持的操作数类型。

Any help will be appreciated. 任何帮助将不胜感激。 Thanks 谢谢

This line is putting the key (the date) in the key variable, and the values, as a list in values. 该行将键(日期)放在键变量中,将值作为值列表 So values will indeed contain something like ['AA' 'BB' 'AAPL']. 因此,值确实会包含类似['AA''BB''AAPL']的内容。

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

Next, you're telling writerow "write a row with two elements: the first is the key, the second is whatever is in values" (which is a list so it's just converted to a string representation and output like that). 接下来,你告诉作者“写一行有两个元素:第一个是键,第二个是值中的任何东西”(这是一个列表,所以它只是转换为字符串表示和输出)。

    w.writerow([key,values])

so [key, values] looks like this: 所以[key,values]看起来像这样:

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

What you'd want, I think, is to create a single list containing the key and strings, not one containing the key and a list of strings. 我想,你想要的是创建一个包含键和字符串的列表,而不是包含键和字符串列表的列表。 You could extend a list with the extra values like so: 您可以使用额外的值扩展列表,如下所示:

    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) does: Extend the list by appending all the items in the given list. list.extend(L)确实:通过附加给定列表中的所有项来扩展列表。

Am sorry if I read this wrong, but are you using python pandas? 很抱歉,如果我读错了,你使用的是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." “我有一个字典,其中包含作为关键字的pandas时间日期和值,>与那些日期为字符串格式的公司。”

in that case something like this might work 在这种情况下,这样的事情可能会奏效

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

the to_csv method be default uses ',' as a delimiter which you can change if needed. to_csv方法默认使用','作为分隔符,您可以根据需要进行更改。

You may need to put something like this: 你可能需要这样的东西:

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

",".join(values) will split the list of values into a string delimited by commas. ",".join(values)会将值列表拆分为由逗号分隔的字符串。 I'm assuming you want commas separating your columns because you are writing a csv file, even though in your example the columns are separated by tab. 我假设你想要用逗号分隔你的列,因为你正在写一个csv文件,即使在你的例子中,列是由制表符分隔的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python csv(两列:键/值)到字典 - Python csv(Two columns: key/value) to Dictionary Python 2.7-将CSV的每一行存储为单独的列表/字典 - Python 2.7- Storing Each Row Of A CSV As A Separate List/Dictionary 如何将字典保存到每个键都有不同行的 csv - How to save a dictionary to a csv where each key has a different row 如何将 CSV 读入 Python 字典,其中每个键的值都是字典列表? - How can I read a CSV into a Python dictionary, where each key's value is a list of dicts? Python Print字典键,值是列表时的值。 在单独的行上打印每个键,值 - Python Print dictionary key, value when value is a list. Print each key, value on seperate line Python:当一个键有多个值时,如何将字典写入csv文件,每个键是一个新行,但每个值是一个新列? - Python: How to write dictionary to csv file when one key has multiple values, each key is a new row, but each value is a new column? Python:将字典打印到csv,每个键值都换行 - Python: print dictionary to csv, each key value in a new line 写密钥以根据字典中的值分隔CSV - Write key to separate csv based on value in dictionary 创建一个 Python 字典,其中每个键都有一个列表作为值 - create a Python dictionary where for each key has a list as the value Python字典转csv,但所有键均作为单独的列 - Python Dictionary to csv , but all keys as seperate individual columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM