Can you append to a dictionary from a foreign python file?

Viewed 58

So I have a project I'm working on for fun but it requires me to append to a dictionary from another python file. In file1.py it will look like

Name: Eric <-- user input
Age: 27 <-- user input

and file2.py,

information = {'Eric':27}

I know that I can temporarily append to a dictionary while running the code, but it seems to reset after I close the program. Like recently I've seen this on a StackOverflow question

d = {'key': 'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'key': 'value', 'mynewkey': 'mynewvalue'}

But this too, resets after every run so I thought that the only way to save the dictionary is to write it to another file. Is there any way that I can achieve this or maybe a better alternative?

1 Answers

You can use JSON to save data to a file.

This will save the data, that is stored in your dictionary, in a file.

import json

my_dict = {"key": "value", "key2": "value2"}

with open("output_file.txt", "w") as file:
    json.dump(my_dict, file, indent=4)

To use that data again, you can load that file.

import json

with open("output_file.txt") as file:
    my_dict = json.load(file)

print(my_dict)  # Will print {"key": "value", "key2": "value2"}

JSON stands for JavaScriptObjectNotation, and it's a way to save data in a string format (a file)

So JSON can convert a string into data, if it is valid JSON:

import json

string_data = '{"key": "value"}'
dictionary = json.loads(string_data)

print(type(string_data))  # <class 'str'>
print(type(dictionary))  # <class 'dict'>
Related