You can use csv's dictionary writer for this, simply do a:
import csv
csv.DictWriter(open("path/to/writefile.csv", "wb"), fieldnames = dict_to_write[dict_to_write.keys()[0]].keys(), delimiter = ","
")
alternatively you can use pandas as a more easier option:
import pandas as pd
pd.DataFrame(dict_to_write).to_csv("file.csv")
for you particular use case, assuming the sample you have given is in a file:
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")
With some editing I think i was able to work with your example
with open(dirforR, 'a') as f:
writer = csv.writer(f)
writer.writerow(['Subject', 'value1', 'concussion'])
for row in sorted_combined:
if len(row) == 0:
pass
else:
l = [val[0]
for val in row.items()
]
for value in list([val[0]
for val in row.values()
][0]):
l.append(value)
writer.writerow(l)
I've been trying to save my dictionary to a anycodings_csv csv file. So I want it to look something anycodings_csv like this: ,***EDIT2 ***this is the code that was used anycodings_csv to make my defaultdict list called: anycodings_csv network_combined,for you particular use case, assuming anycodings_list the sample you have given is in a file:,the reason for this is because I was merging anycodings_csv two dictionaries together and this was the anycodings_csv only way I was able to go about it.. Now I'm anycodings_csv not quite sure how to move my dictionary anycodings_csv list to a csv file.
I've been trying to save my dictionary to a anycodings_csv csv file. So I want it to look something anycodings_csv like this:
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
The dictionary looks like this:
{} {} {} {} {} {} {
'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')]
}
The code I've been using to achieve this anycodings_csv looks like the following (but unfortunately anycodings_csv it hasn't been working):
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)
***EDIT2 ***this is the code that was used anycodings_csv to make my defaultdict list called: anycodings_csv 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)')
}
You can use csv's dictionary writer for anycodings_list this, simply do a:
import csv
csv.DictWriter(open("path/to/writefile.csv", "wb"), fieldnames = dict_to_write[dict_to_write.keys()[0]].keys(), delimiter = ","
")
alternatively you can use pandas as a anycodings_list more easier option:
import pandas as pd
pd.DataFrame(dict_to_write).to_csv("file.csv")
for you particular use case, assuming anycodings_list the sample you have given is in a file:
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")
With some editing I think i was able to anycodings_list work with your example
with open(dirforR, 'a') as f:
writer = csv.writer(f)
writer.writerow(['Subject', 'value1', 'concussion'])
for row in sorted_combined:
if len(row) == 0:
pass
else:
l = [val[0]
for val in row.items()
]
for value in list([val[0]
for val in row.values()
][0]):
l.append(value)
writer.writerow(l)
Saving Defaultdictlist To A Csv File,I've been trying to save my dictionary to a csv file. So I want it to look something like this: , Tags: dictionary , python , list , csv Answers: | Viewed 2,273 times ,the reason for this is because I was merging two dictionaries together and this was the only way I was able to go about it.. Now I'm not quite sure how to move my dictionary list to a csv file.
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
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)
sorted_combined = defaultdict(list)
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)')
}
This is what ended up solving it!,Efficient way to create dictionary from pandas column with list entries where list elements are keys,How do I convert a list of dictionaries formatted this way to a dataframe looking like as shown below? (without hard-coding),Pandas, list of dictionaries where values are a list. Convert dictionary keys into column names. Convert each element in value list to a row
This is what ended up solving it!
names = list(dic1['Address_1'][0].keys())
f.close()
with open("file.csv", "w", newline = "") as f:
writer = csv.writer(f)
keys = names
writer.writerow(["Address"] + (keys))
for k, vl in defaultdict.items():
for v in vl:
writer.writerow([k] + [v[key]
for key in keys
])
f.close()
Your input data and output data do not match, so it's awfully difficult to tell how to transform things, but here is something that takes your defaultdict and converts it to a CSV file:
import csv
dic1 = {
'Address_2': [{
'Address 1': [{
'Name': 'name',
'Address_match': 'address_match_1',
'ID': 'id',
'Type': 'abc'
}]
},
{
'Address 2': [{
'Name': 'name',
'Address_match': 'address_match_2',
'ID': 'id',
'Type': 'abc'
}]
},
{
'Address 3': [{
'Name': 'name',
'Address_match': 'address_match_3',
'ID': 'id',
'Type': 'abc'
}]
}
]
}
names = list(dic1['Address_2'][0]['Address 1'][0].keys())
myfile = csv.DictWriter(open('xxx.csv', 'w'), fieldnames = names)
for row in dic1['Address_2']:
myfile.writerow({
'Name': list(row.keys())[0]
})
myfile.writerow(list(row.values())[0][0])