[英]How to save data as csv file from a dictionary containing keys and lists containing data to respective keys
I need some help on how to save data as a csv file consisting of keys with respective data in colon form. 我需要一些有关如何将数据另存为csv文件的帮助,该文件由具有各自冒号形式的键的键组成。 My code does this only if the dictionary contains one key and one list, but if i have more keys and more lists, the code manages to save the keys as i want them, that is to say, as rows but the data from all lists is saved in the first key.
我的代码仅在字典包含一个键和一个列表的情况下执行此操作,但是如果我有更多的键和更多的列表,则代码会设法将键保存为我想要的键,也就是说,保存为行,但是所有列表中的数据保存在第一个键中。 Any ideas are really appreciated
任何想法都非常感谢
I've tried googling most answers on csv file writing but I haven't found any that resolves my issue 我已经尝试过搜索有关csv文件编写的大多数答案,但没有找到能解决我的问题的任何答案
The code is as follows: 代码如下:
with open('C:/Users/..../Voltage.csv','wb') as csvFile:
output = csv.writer(csvFile, delimiter=';', quoting = csv.QUOTE_ALL)
output.writerow(voltdict.keys())
for item,value in voltdict.iteritems():
for k in value:
output.writerow(localize_float([k]))
csvFile.close()
This an example of what i wish to accomplish: 这是我希望完成的一个示例:
key1 key2 keyn
123 232 253
245 398 ..n
Voltdict is my dictionary and it looks like this: Voltdict是我的字典,它看起来像这样:
{'key1': [list1] 'key2': [list2] 'key:n' : [listn]}
This is an example of what i get with more than one key and more than one list 这是我使用多个按键和多个列表的示例
key1 key2 key:n
122
245
232
398
253
..n
Just convert your dictionary to a pandas dataframe, then use to csv. 只需将字典转换为pandas数据框,然后将其用于csv。 See below
见下文
import pandas as pd
df=pd.DataFrame(my_dictionary)
df.to_csv(file_name)
When creating a DataFrame, simply pass a dictionary into the function, and the data should be structured properly. 创建DataFrame时,只需将字典传递到函数中即可,并且数据的结构应正确。 Here is an example
这是一个例子
list1=[2,3,4]
list2=[2,3,4]
listn=[1,2,3]
dictionary={'key1': list1, 'key2': list2, 'keyn' : listn}
df=pd.DataFrame(dictionary)
which outputs 哪个输出
key1 key2 keyn
0 2 2 1
1 3 3 2
2 4 4 3
Looking at your code i see two problems. 查看您的代码,我看到两个问题。 First, you need commas between your keys when you create a dictionary.
首先,创建字典时,键之间需要用逗号隔开。 Second, if
list1
, list2
and listn
are already lists when they are defined, then you don't need additional brackets around them. 其次,如果
list1
, list2
和listn
在定义它们时已经是列表,那么您就不需要在它们周围附加括号。 Doing this would create a list of lists where the out list has only one entry. 这样做会创建一个列表列表,其中out列表只有一个条目。
If you have any other issues let me know 如果您还有其他问题,请通知我
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.