954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Create a dictionary from a text file - issue with spaces in columns

Hi,

Thank you for your help in advance, i am trying to create a dictionary, the code below works fine if I have two columns in each row with no spaces, however one of the columns data natively has spaces in it e.g.

Sarah me hy uuuuu

at the moment it works if I do

Sarah me_hy_uuuuu

However this isnt perfect for us. How do I get python to break the data into two columns based on only the first space?

fname = r"C:\blah3.txt"
A_dict = {}
for line in open(fname):
    name, score = line.split()
    A_dict[name] = str(score)
print (A_dict)


Many Thanks for the help,

Oliver

oli82
Newbie Poster
4 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
 

Use split with second argument 1 or partition.

>>> "Sarah me hy uuuuu".split(" ", 1)
['Sarah', 'me hy uuuuu']
>>> "Sarah me hy uuuuu".split(None, 1)
['Sarah', 'me hy uuuuu']
>>> "Sarah me hy uuuuu".partition(' ')
('Sarah', ' ', 'me hy uuuuu')
>>>
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

Thanks for the quick reply.

I am really new to python I am sorry but if you could possibly spell it out for me that would be a real help.

I dont understand what to do how do I reference that line and then split it within the context of my code - is it like below?

Many Thanks for the help

>>> fname = r"C:\Users\oliverm\Desktop\GIS1\blah3.txt"
... A_dict = {}
... for line in open(fname):
...     name, score = line.split(" ",1)
...     A_dict[name] = str(score)
... print (A_dict)
... 
Runtime error <type 'exceptions.ValueError'>: need more than 1 value to unpack
>>>
oli82
Newbie Poster
4 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
 

Hi,

I got this to work by using the following code:

fname = r"C:\Users\oliverm\Desktop\GIS1\blah3.txt"
A_dict = {}
for line in open(fname):
    name, score = line.split(",",1)
    A_dict[name] = str(score)
print (A_dict)


However the value in the second column includes \n in the text result, how do I remove this.

Many Thanks for your help,

Oliver

oli82
Newbie Poster
4 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
 

sorted now, many thanks

line = line.strip()

oli82
Newbie Poster
4 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: