I wish to write my dict of list to a csv file, I need to sort my row by key name:
import csv
dict_of_list = {"key1": [1,2,3], "key2": [4,5,6], "key3": [7,8,9]}
#line bugged corrected bellow:
# keys = sorted(dict_of_list.keys())
writer.writerows(sorted([k, *vs] for k, vs in dict_of_list.items()))
with open("P:/Code/Python/CSV/dict_of_list.csv", "w") as tmp:
writer = csv.writer(tmp)
writer.writerows(zip(dict_of_list.items()))
I need the csv file to be ordered like:
key1, 1, 2, 3
key2, 4, 5, 6
key3, 7, 8, 9
Actualy my output csv is:
"('key1', [1, 2, 3])"
"('key2', [4, 5, 6])"
"('key3', [7, 8, 9])"
I've tried other code but I could only put the keys in the header or no keys at all.
I would be grateful if someone could give me a push.
The problem is you are writing the tuples, do this instead:
import csv
dict_of_list = {"key2": [4, 5, 6], "key3": [7, 8, 9], "key1": [1, 2, 3], }
with open("output.csv", "w") as tmp:
writer = csv.writer(tmp)
writer.writerows([k, *vs] for k, vs in sorted(dict_of_list.items()))
Output
key1,1,2,3
key2,4,5,6
key3,7,8,9
The expression:
[k, *vs] for k, vs in dict_of_list.items()
creates a list where the first element is the key and the rest of the elements are the values. Update The *vs
unpacks the elements of the list, see here . If you want the elements sorted by key, do this, as suggested by @tdelaney:
writer.writerows(sorted([k, *vs] for k, vs in dict_of_list.items()))
Instead of managing the writing of the file all by yourself you could use the pandas
library instead.
For that you simply create a pandas DataFrame (like a table) from your dictionary with the orientation set to orient=index
, because your dictionary keys should serve as the rows of your table. Then you simply use the DataFrame method to_csv
to write your csv file. You can use the header=False
parameter when you do not want a header.
import pandas as pd
df = pd.DataFrame.from_dict(dict_of_list, orient="index").sort_index()
df.to_csv("test.csv", sep=";", header=False)
The problem can also be solved using pandas's method to_csv()
import pandas
dict_of_list = {"key1": [1,2,3], "key2": [4,5,6], "key3": [7,8,9]}
df = pandas.DataFrame(dict_of_list)
df.T.sort_index().to_csv("test.csv",sep=";",header=False)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.