Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - converting textfile contents into dictionary values/keys easily

Let's say I have a text file with the following:

line = "this is line 1"
line2 = "this is the second line"
line3 = "here is another line"
line4 = "yet another line!"

And I want to quickly convert these into dictionary keys/values with " line* " being the key and the text in quotes as the value while also removing the equals sign.

What would be the best way to do this in Python?

like image 688
jim Avatar asked May 09 '11 21:05

jim


People also ask

How do you turn a string of a dictionary into a dictionary?

To convert a string to dictionary, we have to ensure that the string contains a valid representation of dictionary. This can be done by eval() function. Abstract Syntax Tree (ast) module of Python has literal_eval() method which safely evaluates valid Python literal structure.

How do I convert a CSV file to a dictionary in Python?

The best way to convert a CSV file to a Python dictionary is to create a CSV file object f using open("my_file. csv") and pass it in the csv. DictReader(f) method. The return value is an iterable of dictionaries, one per row in the CSV file, that maps the column header from the first row to the specific row value.

Can strings be used as dictionary keys?

Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key.


2 Answers

f = open(filepath, 'r')
answer = {}
for line in f:
    k, v = line.strip().split('=')
    answer[k.strip()] = v.strip()

f.close()

Hope this helps

like image 137
inspectorG4dget Avatar answered Oct 11 '22 00:10

inspectorG4dget


In one line:

d = dict((line.strip().split(' = ') for line in file(filename)))
like image 27
Peter Collingridge Avatar answered Oct 10 '22 23:10

Peter Collingridge