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

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')
>>>

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
>>>

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

sorted now, many thanks

line = line.strip()

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.