简体   繁体   中英

How to save a dictionary with lists to a csv file

I have a dictionary with two keys and a list with each key and was wondering how I could save the lists, with each key representing a column of the values within the list? The values are all Decimal('x') by the way.

An example of my dictionary is

mydict = {'Prices':[Decimal('1'),Decimal('2')], 'Quantities':[Decimal('4.3'), Decimal('2.2')]}

Overall goal is to save the dictionary and read in again to be back to how it was in another program

The simplest way to do this is to convert it into a DataFrame like so:

mydict = {'Prices':[1, 2], 'Quantities':[4.3, 2.2]}
#I didn't have the Decimal function defined.

df = pd.DataFrame(mydict)
df.to_csv('save.csv')

#reading it in
read = pd.read_csv('save.csv')[['Prices', 'Quantities']].to_dict()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM