Reputation: 1
I am working on a project where I am using Dictionary as a Database for storing the objects. However, I am not getting way got get into the Dictionary which is in Text file and unable to add more items inside.
My Text File:
a = {1:2,2:1}
My Code: I am unable to find way to get way to append more items inside that dictionary.
Upvotes: 0
Views: 752
Reputation: 684
Just an example, you can do many more things with python dictionary. Refer here for more: https://www.w3schools.com/python/python_dictionaries.asp
a = {
"Index": 1,
"Model": "2019",
1: 2,
2:1
}
import json
with open('file.txt', 'w') as file: # Writing to file here
file.write(json.dumps(a))
file.close()
with open('file.txt') as file: # Reading the file here
data = json.load(file)
print (data)
file.close()
data["type"] = "dictionary" # Adding item to dictionary
print(data)
Output before adding item:
{'Index': 1, 'Model': '2019', '1': 2, '2': 1}
Output after adding item:
{'Index': 1, 'Model': '2019', '1': 2, '2': 1, 'type': 'dictionary'}
Upvotes: 1