0

I want to save my dictionary to a file in a way that it can be easily imported afterwards keeping its dictionary meaning. If I do the following:

def save_dict_to_file(dic):
    f = open('dict.txt','w')
    f.write(str(dic))
    f.close()

And then, if I want to load the dict from the file, by doing this:

d={}
fi=open("dict.txt","r")
lineinfile=fi.readlines()
d=lineinfile
print(type(d))

The result I obtain is a list, not a dictionary. Without using any module, how can this be solved? Was my error when exporting the dictionary or when importing it?

Paul Roberts
  • 119
  • 6
  • 2
    1. ```readlines``` function returns all the lines from the file as a list. 2. the returned list elements will be strings, so you actually need to convert str to dict - in the simplest case try [this](https://stackoverflow.com/a/41329284/7769691). – Yulian Feb 19 '21 at 18:21

2 Answers2

1

You can use json from standard library

import json

data = {'a': 1, 'b': 2}

# Save data
with open('output_name.json', 'w') as f:
    json.dump(data, f)

# Read data
with open('output_name.json', 'r') as f:
    data = json.load(f)

If you want to do this yourself (without json module), it is not that straightforward. You can look at json source code how it is being done https://github.com/python/cpython/tree/3.9/Lib/json

Robert Axe
  • 396
  • 2
  • 11
0

You are using readlines() function which returns a list containing each line in the file as a list item

Kyve
  • 32
  • 1
  • 3
  • Is the only way I could think of without using json or other modules. Any suggestion on how this can be done without them? – Paul Roberts Feb 19 '21 at 18:47