通过 Python 将不同大小列表的字典写入 CSV
Write dictionary of different size lists to a CSV via Python
我想编写以下 python 词典:
dicty = {'Odd': [1,3,5,7,9], 'Even': [2,4,6], 'Operations': ['-','+','*','\']}
CSV 文件,格式如下:
当前代码:
import csv
dicty = {'Odd': [1,3,5,7,9], 'Even': [2,4,6], 'Operations': ['-','+','*','\']}
with open('data.csv', 'w') as f:
for key in dicty.keys():
f.write("%s, %s\n" % (key, dicty[key]))
产量:
您可以使用此代码:
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)
我想编写以下 python 词典:
dicty = {'Odd': [1,3,5,7,9], 'Even': [2,4,6], 'Operations': ['-','+','*','\']}
CSV 文件,格式如下:
当前代码:
import csv
dicty = {'Odd': [1,3,5,7,9], 'Even': [2,4,6], 'Operations': ['-','+','*','\']}
with open('data.csv', 'w') as f:
for key in dicty.keys():
f.write("%s, %s\n" % (key, dicty[key]))
产量:
您可以使用此代码:
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)