How to save a dictionary to a file?

I have a problem with changing the dict value and saving the dict in a text file (the format should be the same), I only want to change the member_phone field.

My text file has the following format:

 memberID:member_name:member_email:member_phone 

and I split the text file into:

 mdict={} for line in file: x=line.split(':') a=x[0] b=x[1] c=x[2] d=x[3] e=b+':'+c+':'+d mdict[a]=e 

When I try to change the member_phone stored in d , the value is not changed to a stream,

 def change(mdict,b,c,d,e): a=input('ID') if a in mdict: d= str(input('phone')) mdict[a]=b+':'+c+':'+d else: print('not') 

and how to save the dict in a text file in the same format?

+102
python dictionary file
05 Oct '13 at 18:34
source share
9 answers

Python has pickle only for this kind of thing.

These functions are all you need to save and load almost any object:

 def save_obj(obj, name ): with open('obj/'+ name + '.pkl', 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) def load_obj(name ): with open('obj/' + name + '.pkl', 'rb') as f: return pickle.load(f) 

These functions assume that you have an obj folder in the current working directory that will be used to store objects.

Note that pickle.HIGHEST_PROTOCOL is a binary format that may not always be convenient, but good for performance. Protocol 0 is a text format.

There is a shelve module to save Python collections.

+209
Oct 05 '13 at 18:50
source share

Pickle is probably the best option, but if anyone wonders how to save and load the dictionary into a file using NumPy:

 import numpy as np # Save dictionary = {'hello':'world'} np.save('my_file.npy', dictionary) # Load read_dictionary = np.load('my_file.npy').item() print(read_dictionary['hello']) # displays "world" 

FYI: NPY File Viewer

+136
Aug 26 '15 at 0:05
source share

I'm not sure what your first question is, but if you want to save the dictionary to a file, you should use the json library. View the documentation for the loads and arrange the functions.

+16
05 Oct '13 at 18:43
source share

Save and load the dict file into a file:

 def save_dict_to_file(dic): f = open('dict.txt','w') f.write(str(dic)) f.close() def load_dict_from_file(): f = open('dict.txt','r') data=f.read() f.close() return eval(data) 
+9
Aug 27 '18 at 17:57
source share

We can also use the json module when dictionaries or some other data can be easily mapped to the JSON format .

Serializing data to a file:

 import json json.dump( data, open( "file_name.json", 'w' ) ) 

Read data from file:

 import json data = json.load( open( "file_name.json" ) ) 

This solution provides many advantages , for example, it works unchanged for Python 2.x and Python 3.x, and in addition, data saved in JSON format can be easily transferred between different platforms or programs . These data are also human readable .

+3
Mar 11 '19 at 19:59
source share

If you really want to save the dictionary, I think the best solution is to use the Python csv module to read the file. Then you get the data rows, and you can change member_phone or whatever you want; finally, you can use the csv module again to save the file in the same format as you opened it.

Code to read:

 import csv with open("my_input_file.txt", "r") as f: reader = csv.reader(f, delimiter=":") lines = list(reader) 

Code for writing:

 with open("my_output_file.txt", "w") as f: writer = csv.writer(f, delimiter=":") writer.writerows(lines) 

Of course you need to adapt your change() function:

 def change(lines): a = input('ID') for line in lines: if line[0] == a: d=str(input("phone")) line[3]=d break else: print "not" 
+2
Oct 05 '13 at 18:59
source share

For a string dictionary, such as the one you're dealing with, this can be done using only Python's built-in text processing capabilities.

(Note that this will not work if the values ​​are something else.)

 with open('members.txt') as file: mdict={} for line in file: a, b, c, d = line.strip().split(':') mdict[a] = b + ':' + c + ':' + d a = input('ID: ') if a not in mdict: print('ID {} not found'.format(a)) else: b, c, d = mdict[a].split(':') d = input('phone: ') mdict[a] = b + ':' + c + ':' + d # update entry with open('members.txt', 'w') as file: # rewrite file for id, values in mdict.items(): file.write(':'.join([id] + values.split(':')) + '\n') 
+2
Oct 05 '13 at 22:22
source share

I did not time it, but I put h5 faster than a pickle; the file size with compression is almost certainly smaller.

 import deepdish as dd dd.io.save(filename, {'dict1': dict1, 'dict2': dict2}, compression=('blosc', 9)) 
+1
Nov 07 '17 at 23:38
source share

Quick and dirty solution: convert dict to string and save to file, for example:

 #dict could be anything: savedict = open('savedict001.txt', 'w') savedict.write(str(dict)) savedict.close() 
+1
Nov 15 '18 at
source share



All Articles