I have the following file dic.txt:
{'a':0, 'b':0, 'c':0, 'd':0}
I want to read its contents and use as a dictionary. After entering new data values I need to write them into that file. Basically I need a script to work with the dictionary, update its values and save them for later use.
I have a working script, but can't figure out how to actually read the contents of the dic.txt into a variable in the script. Cause when I try this:
file = '/home/me/dic.txt'
dic_list = open(file, 'r')
mydic = dic_list
dic_list.close()
What I get as mydic is a str. And I can't manipulate its values. So here is the question. How do I create a dictionary from a dic.txt?
Python dictionary | values() values() is an inbuilt method in Python programming language that returns a view object. The view object contains the values of the dictionary, as a list. If you use the type() method on the return value, you get “dict_values object”. It must be cast to obtain the actual list.
You need to parse the data to get a data structure from a string, fortunately, Python provides a function for safely parsing Python data structures: ast.literal_eval()
. E.g:
import ast
...
with open("/path/to/file", "r") as data:
dictionary = ast.literal_eval(data.read())
You can use the python built-in function eval():
>>> mydic= "{'a':0, 'b':0, 'c':0, 'd':0}"
>>> eval(mydic)
{'a': 0, 'c': 0, 'b': 0, 'd': 0}
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With