Python Forum
Simple Dictionary save and recover
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple Dictionary save and recover
#1
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'}
Reply
#2
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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Many thanks Buran
Just to allow options,can something similar be done for saving as a csv file?

Astrikor
Reply
#4
You can pickle it https://wiki.python.org/moin/UsingPickle
Reply
#5
(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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
Cool.
Thanks Buran.
Reply
#7
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
Reply
#8
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#9
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
Reply
#10
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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to save to multiple locations during save cubangt 1 564 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  simple f-string expressions to access a dictionary Skaperen 0 1,532 Jul-15-2020, 05:04 AM
Last Post: Skaperen
  How to save dictionary sampitosh 3 2,459 Apr-24-2020, 04:43 AM
Last Post: ndc85430
  How to recover from exception in pdb? swimbikerun 1 2,961 Jul-29-2017, 01:51 AM
Last Post: Larz60+
  Recover currently running script? kbriden 3 4,491 Dec-07-2016, 01:53 PM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020