5

I have a .txt file with the following contents:

norway  sweden
bhargama  bhargama
forbisganj  forbesganj
canada  usa
ankara  turkey

I want to overwrite the file such that these are its new contents:

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

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

Here is my attempt:

import re
target = open('file.txt', 'w')

for line in target:
  target.write(re.sub(r'([a-z]+)', r'':'"\1"','', line))

I'm succeeding in getting the quotes; but what's the proper regex to do what I described above?

7
  • why do you want to use regex here there is no need of regex here Commented Oct 19, 2015 at 5:18
  • First thing that came to mind... Is there a more efficient way to do it? Commented Oct 19, 2015 at 5:19
  • will there be only two words separated by space Commented Oct 19, 2015 at 5:20
  • Yes, two words with space, followed by a newline character Commented Oct 19, 2015 at 5:21
  • 5
    d = dict(line.split() for line in open('file.txt')) Commented Oct 19, 2015 at 5:26

1 Answer 1

10

You don't need a regular expression for that.

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 each line in your file and splits it on whitespace into a list. This generator of lists is fed to dict(), which makes each one a dictionary key and value.

>>> my_dictionary['norway']
'sweden'
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the help :)
If you don't use strip(), the value will have '\n' at the end, and I didn't want that.
I tested it (more than once) and found that it did need the strip(). However, I tested it yet again just now and it isn't producing the result I got before. I don't know why the result is different now, but I'll remove it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.