Write dictionary of lists to a CSV file
If you don't care about the order of your columns (since dictionaries are unordered), you can simply use zip()
:
d = {"key1": [1,2,3], "key2": [4,5,6], "key3": [7,8,9]}
with open("test.csv", "wb") as outfile:
writer = csv.writer(outfile)
writer.writerow(d.keys())
writer.writerows(zip(*d.values()))
Result:
key3 key2 key1
7 4 1
8 5 2
9 6 3
If you do care about order, you need to sort the keys:
keys = sorted(d.keys())
with open("test.csv", "wb") as outfile:
writer = csv.writer(outfile, delimiter = "\t")
writer.writerow(keys)
writer.writerows(zip(*[d[key] for key in keys]))
Result:
key1 key2 key3
1 4 7
2 5 8
3 6 9
Write dictionary of lists to csv
I wanted to do the same thing and this is what worked for me. Using the zip with the * operator did the trick for me. Also paying attention to the writerow singular and writerows plural helped write the dictionary into the kind of file I wanted with headers.
zd = zip(*dictionary.values())
with open('file.csv', 'w') as file:
writer = csv.writer(file, delimiter=',')
writer.writerow(dictionary.keys())
writer.writerows(zd)
Output looks like this,
gender,age,state,race,weights,educ
1,39,32,06,0.57,8
2,35,33,06,0.93,5
1,39,11,06,0.83,5
Your example should work exactly the same only change dictionary to be the dictionary with your data in it.
Saving a python dictionary (of lists) in a csv file
If you can use pandas
its very simple.
Demo:
import pandas as pd
d = {"key1": [1,2,3], "key2": [5], "key3": [6,9]}
df = pd.DataFrame.from_dict(d, orient='index')
df = df.transpose()
df.to_csv("test.csv", index=False)
Write dictionary of different size lists to a CSV via Python
You can use this code:
import pandas as pd
dictionary = {'Odd': [1,3,5,7,9], 'Even': [2,4,6], 'Operations': ['-','+','*','\\']}
# These lines are because your lists are not all of the same length
df = pd.DataFrame.from_dict(dictionary, orient='index')
df = df.transpose()
# Pandas was converting the "9" in odd to a float, this undoes that
df["Odd"] = pd.to_numeric(df["Odd"], downcast="integer")
# index = False says don't include the index that pandas slaps onto your data
# This writes to output.csv as you'd expect
df.to_csv("output.csv", index = False)
How to write a dictionary of lists with different length to csv?
import pandas as pd
dic = {'a': ['ACI', 'BBY', 'AMRX'], 'b': ['ABM', 'AG']}
df = pd.DataFrame.from_dict(dic, orient='index') #Convert dict to df
print(df)
df.to_csv("final.csv",header=False) #Convert df to csv
Write list of dictionaries with additional lists to CSV - Python
This type of list of the dictionary is called Nested JSON; it is better to handle this data type to CSV with Pandas method json_normalize
:
import pandas as pd
test = [{
'name': 'name_1',
'id': 'id_1',
'info': [{
'info_1': 'some info',
'info_2': 'more info'
},
{
'info_1': 'all the info',
'info_2': 'extra info'
}]
},
{
'name': 'name_2',
'id': 'id_2',
'info': [{
'info_1': 'another piece of info the same type as info_1 above',
'info_2': 'info'
},
{
'info_1': 'getting tedious',
'info_2': 'you get the picture...'
}
]
}]
df = pd.json_normalize(test, 'info', ['id', 'name'],
record_prefix='information_')
df.to_csv('information.csv')
final result(screenshot):
*: it is better to use Pandas for this problem instead of CSV standard library because if you have a large file, 2 iteration to handle this problem has much time processing.
Convert dictionary of lists to a CSV file using Python
Why are you trying to use a dictionary? You can use the csv
module and write those lists directly.
import csv
header_column = ["id", "data"]
text = ["1, first", "2, second", "3, third"]
with open('sample.tsv', 'wb') as f:
writer = csv.writer(f, delimiter='\t')
writer.writerow(header_column)
for l in text:
writer.writerow(l.split(', '))
This works as expected, giving
id data
1 first
2 second
3 third
Do note for excel to understand that your code is tab separated, you need to save it as a .tsv
file.
Related Topics
Most Efficient Way to Search the Last X Lines of a File
How to Set Ticks on Fixed Position , Matplotlib
In Python, How Does One Catch Warnings as If They Were Exceptions
Using Django Database Layer Outside of Django
How to Wrap Every Method of a Class
Error: Pg_Config Executable Not Found When Installing Psycopg2 on Alpine in Docker
Why Can't I Repeat the 'For' Loop for CSV.Reader
Remove Duplicate Rows from Pandas Dataframe Where Only Some Columns Have the Same Value
How to Add Static(Html, CSS, Js, etc) Files in Pyinstaller to Create Standalone Exe File
How to Change the Host and Port That the Flask Command Uses
How to Install a Package Inside Virtualenv
Matplotlib Scatter Plot with Legend