Python - converting text file contents to 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 them into dictionary keys / values, with the string * key being the key, and the text in quotation marks as the value, as well as removing the equal sign.

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

+6
source share
3 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

+15
source

In one line:

 d = dict((line.strip().split(' = ') for line in file(filename))) 
+4
source

The urlopen version of the urlopen response will look here:

 from urllib.request import urlopen url = 'https://raw.githubusercontent.com/sedeh/imtqy.com/master/resources/states.txt' response = urlopen(url) lines = response.readlines() state_names_dict = {} for line in lines: state_code, state_name = line.decode().split(":") state_names_dict[state_code.strip()] = state_name.strip() 
0
source

Source: https://habr.com/ru/post/887666/


All Articles