Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 3 saving a dictionary

I have looked at other questions on SO like this one but they are too techy for me to understand (only been learning a few days). I am making a phonebook and i am trying to save a dictionary like so,

numbers = {}
def save(a):
   x = open("phonebook.txt", "w")
   for l in a:
       x.write(l, a[l])
   x.close()

But i get error write() only takes 1 argument and obv im passing 2, so my question is how can i do this in a beginner freindly way and could you describe it in a non techy way. Thanks a lot.

like image 980
StandingBird Avatar asked Dec 26 '22 21:12

StandingBird


2 Answers

It's better to use json module for dumping/loading dictionary to/from a file:

>>> import json
>>> numbers = {'1': 2, '3': 4, '5': 6}
>>> with open('numbers.txt', 'w') as f:
...     json.dump(numbers, f)
>>> with open('numbers.txt', 'r') as f:
...     print json.load(f)
... 
{u'1': 2, u'3': 4, u'5': 6}
like image 112
alecxe Avatar answered Feb 13 '23 03:02

alecxe


While JSON is a good choice and is cross-language and supported by browsers, Python has its own serialization format called pickle that is much more flexible.

import pickle

data = {'Spam': 10, 'Eggs': 5, 'Bacon': 11}

with open('/tmp/data.pickle', 'w') as pfile:
    pickle.dump(data, pfile)

with open('/tmp/data.pickle', 'r') as pfile:
    read_data = pickle.load(pfile)

print(read_data)

Pickle is Python-specific, doesn't work with other languages, and be careful to never load pickle data from untrusted sources (such as over the web) as it's not considered "safe".

Pickle works for other data types too, including instances of your own classes.

like image 28
cellofellow Avatar answered Feb 13 '23 03:02

cellofellow