Python Forum

Full Version: Simple Dictionary save and recover
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
I have searched several posts on saving dictionaries, but not found anything suitable for saving and subsequently recovering a simple dictionary.

Can anyoine advise how to save this to a file (any suitable type) and then to recover it to a Python program at a later date:
Dict = {'A': 2, 'B': 12,'C':65,'D':'Plc'}
json module
import json

def save_as_json(my_json, file_name):
    with open(file_name, 'w') as f:
        f.write(json.dumps(my_json, indent=4, sort_keys=True))
        
def read_json(file_name):
    with open(file_name, 'r') as f:
        return json.load(f)
   
if __name__ == '__main__':
    d = {'A': 2, 'B': 12,'C':65,'D':'Plc'}
    file_name = 'example.json'
    
    # save as json
    save_as_json(my_json=d, file_name=file_name)
    
    # read from json
    new_d = read_json(file_name=file_name)
    print(new_d['D'])
EDIT: In save_as_json function I was using the global variable d, not the argument I pass my_json. Now it is fixed.
Many thanks Buran
Just to allow options,can something similar be done for saving as a csv file?

Astrikor
(Aug-08-2018, 09:09 PM)Astrikor Wrote: [ -> ]ust to allow options,can something similar be done for saving as a csv file?
Sure you can. For example using csv module, more convenient.
import csv

def save_as_csv(save_dict, file_name):
    with open(file_name, 'w') as f:
        wrtr = csv.DictWriter(f, fieldnames=save_dict.keys())
        wrtr.writeheader()
        wrtr.writerow(save_dict)

def read_csv(file_name):
    with open(file_name, 'r') as f:
        return next(csv.DictReader(f))

if __name__ == '__main__':
    d = {'A': 2, 'B': 12,'C':65,'D':'Plc'}
    file_name = 'example.csv'

    # save as csv
    save_as_csv(save_dict=d, file_name=file_name)

    # read from csv
    new_d = read_csv(file_name=file_name)
    print(new_d['D'])
Of course you can write the file as normal file, without csv module.
As wooee sugested another option is to use pickle.

By the way, I noticed I have an error in the json example from post#2. In save_as_json function I was using the global variable d, not the argument I pass my_json. Now it is fixed.
Cool.
Thanks Buran.
I have noticed that text gets left justified in the CSV file generated.
Is it possible to save to CSV with right justification?

Thanks

Astrokir
there is no such thing as right or left justification when you work with csv file. It's plain text file.
To get something to look right-justified, you need to fill the string on left side with spaces. So you would be dealing with fixed width file, mixed with csv
Well that's odd.
If you run your code (as above) and open example.csv the numbers appear on the right side of the columns, whereas the text appears on the left side. Evidently numbers and text are treated differently, hence my question.
Maybe it's not to do with CSV file structure per-se, but perhaps to do with it's compilation in Python ?

Astrikior
Open the csv file in simple text editor as Notepad or Notepad++ and you will see what CSV really looks like. In the text file everything is text.
I guess you open it with Excel, and Excel converts what look like numbers to numbers. It takes the decision based on the top several rows and that is why you see them right-aligned. However this is the csv processed by excel.
Pages: 1 2