Bob Smith Bob Smith - 4 months ago 9
Python Question

Python Text to Dictionary doesn't work

I have the following text file in the same folder as my Python Code.

78459581
Black Ballpoint Pen
12345670
Football
49585922
Perfume
83799715
Shampoo


I have written this Python code.

file = open("ProductDatabaseEdit.txt", "r")
d = {}
for line in file:
x = line.split("\n")
a=x[0]
b=x[1]
d[a]=b

print(d)


This is the result I receive.

b=x[1]
IndexError: list index out of range


My dictionary should appear as follows:

{"78459581" : "Black Ballpoint Pen"
"12345670" : "Football"
"49585922" : "Perfume"
"83799715" : "Shampoo" }


What am I doing wrong?

Thanks.

Answer

You need to strip the \n, not split

file = open("products.txt", "r")
d = {}
for line in file:
    a = line.strip()
    b = file.next().strip()
    # next(file).strip() # if using python 3.x
    d[a]=b

print(d)

{'12345670': 'Football', '49585922': 'Perfume', '78459581': 'Black Ballpoint Pen', '83799715': 'Shampoo'}