+ 2

Save Dictionary values to a file?

I'm very new, but is there a way to save Dictionary values to a file? I don't want the file to be rewritten, just added on to. I thought about converting the values into strings but I'm not sure how to do that... Here's an example of what I've got dict = {} dict[1] = 'a'; dict[2] = 'b'; dict[3] = 'c'; f = (r"letter.txt") f.open(r"letter.txt", "a") f.write(str(dict[3])) f.close I get an error, but is there a better way to do this?

10th Mar 2020, 11:38 PM
Liren SQ
Liren SQ - avatar
4 Réponses
+ 5
With pickle module, you can save data types directly. (Pickle does the necessary steps for you.) The whole object with its contents will be stored and recreated when you load it later.
11th Mar 2020, 1:03 AM
HonFu
HonFu - avatar
+ 5
Dictionaries cannot be directly encoded into a file. You probably have to do string manipulation. Therefore, you need to format your data. For example, you store each entry as: {key}: {value} Then, with open("text.txt", "w") as file: for i in dict: file.write(f"{i}: {dict[i]}")
11th Mar 2020, 12:46 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
11th Mar 2020, 2:25 AM
Vitaly Sokol
Vitaly Sokol - avatar
+ 2
Are you getting an error on a computer or sololearn code playground?
11th Mar 2020, 12:08 AM
Gordon
Gordon - avatar