Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read dictionary data from a file in python?

Tags:

python

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?

like image 925
minerals Avatar asked Dec 10 '12 21:12

minerals


People also ask

How do I fetch a dictionary value?

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.


2 Answers

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())
like image 191
Gareth Latty Avatar answered Sep 22 '22 13:09

Gareth Latty


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}
    >>> 
like image 43
Dinesh Avatar answered Sep 22 '22 13:09

Dinesh