我一直试图将字典保存到csv文件中。所以我希望它看起来像这样:
Subject value1 concussion
network3_UCA_0073_01_(0, 1) 0.57 no
network3_UCA_0073_02_(0, 1) 0.64 no
network3_UCA_0073_03_(0, 1) 0.59 no
network3_UCA_0075_01_(0, 1) 0.69 no
字典如下:
{}
{}
{}
{}
{}
{}
{'network3_UCA_0073_01_(0, 1)': [(0.57, 'no')]}
{'network3_UCA_0073_02_(0, 1)': [(0.64, 'no')]}
{'network3_UCA_0073_03_(0, 1)': [(0.59, 'no')]}
{}
{}
{'network3_UCA_0075_01_(0, 1)': [(0.69, 'no')]}
{'network3_UCA_0075_02_(0, 1)': [(0.62, 'no')]}
{'network3_UCA_0075_03_(0, 1)': [(0.57, 'no')]}
{'network3_UCA_0076_01_(0, 1)': [(0.38, 'no')]}
{'network3_UCA_0076_02_(0, 1)': [(0.60, 'no')]}
{'network3_UCA_0076_03_(0, 1)': [(0.68, 'no')]}
{'network3_UCA_0077_01_(0, 1)': [(0.64, 'no')]}
{'network3_UCA_0077_02_(0, 1)': [(0.58, 'no')]}
{'network3_UCA_0077_03_(0, 1)': [(0.48, 'no')]}
我一直用来实现此目的的代码如下(但不幸的是,它没有起作用):
with open(dirforR , 'a') as f:
writer = csv.writer(f)
writer.writerow(['Subject', 'value1', 'concussion'])
for row in sorted_combined:
#print row[0]
l = [row[0]]
l.append(row[1][0])
l.append(row[1][1])
writer.writerow(l)
我不确定是否是因为字典的键由\ n分隔,但是任何帮助将不胜感激。我试图解决这个问题没有希望。
感谢您的帮助。我希望很快能收到答复。 *********编辑***********
我意识到这不是普通的字典,实际上我将其设置为:
sorted_combined = defaultdict(list)
之所以这样,是因为我将两个词典合并在一起,而这是我能够解决的唯一方法。 现在我不太确定如何将字典列表移动到csv文件中。
对不起,这有点混乱。
*** EDIT2 ***这是用于创建我的defaultdict列表的代码,称为:network_combined
network3 = defaultdict(list)
combined_MDD = {key : (MDD_network3[key], MDD_network3_yesno[key]) for key
in MDD_network3}
combined_HC = {key : (HC_network3[key], HC_network3_yesno[key]) for key in HC_network3}
for k, v in chain(combined_MDD.items(), combined_HC.items()):
network3[k].append(v)
sorted_combined = {k:v for k,v in network3.items() if k.endswith('(0, 1)')}
答案 0 :(得分:2)
您可以为此使用csv的字典编写器,只需执行以下操作即可:
import csv
csv.DictWriter(open("path/to/writefile.csv","wb"),fieldnames=dict_to_write[dict_to_write.keys()[0]].keys(),delimiter=","")
或者,您可以将熊猫用作更简单的选项:
import pandas as pd
pd.DataFrame(dict_to_write).to_csv("file.csv")
对于您的特定用例,假设您给出的样本在文件中:
import pandas as pd
with open("dictionary.txt","r") as file:
raw_d=file.read().splitlines()
raw_d=[eval(x) for x in raw_d if len(x)>2]
pd.DataFrame([(k,v[0][0],v[0][1]) for x in raw_d for k,v in x.items()]).to_csv("converted_dict.csv")
答案 1 :(得分:1)
通过一些编辑,我认为我能够处理您的示例
fFmpeg.execute('-i video.mp4 -f null /dev/null').then((value) {
print('Got value ');
}).catchError((error) {
print('Error');
});
希望对您有帮助