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?
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.
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.
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.
f = open(filepath, 'r')
answer = {}
for line in f:
k, v = line.strip().split('=')
answer[k.strip()] = v.strip()
f.close()
Hope this helps
In one line:
d = dict((line.strip().split(' = ') for line in file(filename)))
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