Python: regex to make a python dictionary from a sequence of words?

I have a .txt file with the following contents:

norway sweden bhargama bhargama forbisganj forbesganj canada usa ankara turkey 

I want to rewrite the file so that it is its new contents:

 'norway' : 'sweden', 'bhargama': 'bhargama', 'forbisganj' : 'forbesganj', 'canada': 'usa', 'ankara': 'turkey' 

Basically, I want to turn a .txt file into a python dictionary so that I can manipulate it. Are there built-in libraries for this kind of task?

Here is my attempt:

 import re target = open('file.txt', 'w') for line in target: target.write(re.sub(r'([az]+)', r'':'"\1"','', line)) 

I get quotes; but what correct regular expression does what I described above do?

+5
source share
1 answer

You do not need a regular expression for this.

File:

 norway sweden bhargama bhargama forbisganj forbesganj canada usa ankara turkey 

code:

 with open('myfile.txt') as f: my_dictionary = dict(line.split() for line in f) 

This goes through every line in your file and splits it into a space on list . This list generator is fed to dict() , which makes each dictionary key and value.

 >>> my_dictionary['norway'] 'sweden' 
+10
source

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


All Articles