jdmonroe29
jdmonroe29

Reputation: 33

Writing Dictionary to .csv

After looking around for about a week, I have been unable to find an answer that I can get to work. I am making an assignment manager for a project for my first year CS class. Everything else works how I'd like it to (no GUI, just text) except that I cannot save data to use each time you reopen it. Basically, I would like to save my classes dictionary:

classes = {period_1:assignment_1, period_2:assignment_2, period_3:assignment_3, period_4:assignment_4, period_5:assignment_5, period_6:assignment_6, period_7:assignment_7}

after the program closes so that I can retain the data stored in the dictionary. However, I cannot get anything I have found to work. Again, this is a beginner CS class, so I don't need anything fancy, just something basic that will work. I am using a school-licensed form of Canopy for the purposes of the class.

Upvotes: 3

Views: 119

Answers (3)

Cleb
Cleb

Reputation: 26039

The pickle approach described by @Ébe Isaac and @L3viathan is the way to go. In case you also want to do something else with the data, you might want to consider pandas (which you should only use IF you do something else than just exporting the data).

As there are only basic strings in your dictionary according to your comment below your question, it is straightforward to use; if you have more complicated data structures, then you should use the pickle approach:

import pandas as pd

classes = {'period_1':'assignment_1', 'period_2':'assignment_2', 'period_3':'assignment_3', 'period_4':'assignment_4', 'period_5':'assignment_5', 'period_6':'assignment_6', 'period_7':'assignment_7'}

pd.DataFrame.from_dict(classes, orient='index').sort_index().rename(columns={0: 'assignments'}).to_csv('my_csv.csv')

That gives you the following output:

           assignments
period_1  assignment_1
period_2  assignment_2
period_3  assignment_3
period_4  assignment_4
period_5  assignment_5
period_6  assignment_6
period_7  assignment_7

In detail:

.from_dict(classes, orient='index') creates the actual dataframe using the dictionary as in input

.sort_index() sorts the index which is not sorted as you use a dictionary for the creation of the dataframe

.rename(columns={0: 'assignments'}) that just assigns a more reasonable name to your column (by default '0' is used)

.to_csv('my_csv.csv') that finally exports the dataframe to a csv

If you want to read in the file again you can do it as follows:

df2 = pd.read_csv('my_csv.csv', index_col=0)

Upvotes: 1

L3viathan
L3viathan

Reputation: 27333

Either use the csv library, or do something simple like:

with open("assignments.csv", "w") as f:
    for key, value in classes.items():
        f.write(key + "," + value + "\n")

Edit: Since it seems that you can't read or write files in your system, here's an alternative solution (with pickle and base85):

import pickle, base64

def save(something):
    pklobj = pickle.dumps(something)
    print(base64.b85encode(pklobj).decode('utf-8'))

def load():
    pklobj = base64.b85decode(input("> ").encode('utf-8'))
    return pickle.loads(pklobj)

To save something, you call save on your object, and copy the string that is printed to your clipboard, then you can save it in a file, for instance.

>>> save(classes)  # in my case: {34: ['foo#', 3]}
fCGJT081iWaRDe;1ONa4W^ZpJaRN&NWpge

To load, you call load() and enter the string:

>>> load()
> fCGJT081iWaRDe;1ONa4W^ZpJaRN&NWpge
{34: ['foo#', 3]}

Upvotes: 3

Ébe Isaac
Ébe Isaac

Reputation: 12391

L3viathan's post might be direct answer to this question, but I would suggest the following for your purpose: using pickle.

import pickle

# To save a dictionary to a pickle file:
pickle.dump(classes, open("assignments.p", "wb"))

# To load from a pickle file:
classes = pickle.load(open("assignments.p", "rb"))

By this method, the variable would retain its original structure without having to write and convert to different formats manually.

Upvotes: 4

Related Questions