-1

I am reading a file and turning it into a dictionary but cannot get rid of the \n in the dictionary key.

Here is my code:

file = open('textfile.txt')

dct = {line.split(":")[0]:line.split(":")[1] for line in file}

print(dct)

And here is the output:

{'John': 'e6868d7b1cb85386cd8bcca41a87ae22c124421caff73d5934982bf5324ef3f6\n', 'Mary': 'cdc7283def7099d7b1a1479b14bb0b4f4c1dafa5e0d7ca2f971e103c5ca2cf91\n', 'Bob': '50bdd8da1bf88ef117720f9be735459bc61403d9c2d59de9365e47636ed7ecf8\n', 'Jane': '11a4a60b518bf24989d481468076e5d5982884626aed9faeb35b8576fcd223e1\n', 'Peter': 'ef794d0f3a4eb6bf12e7b5d1c554ce14e806096e754d118c0a53b7b3d73b9867\n', 'Julia': '7bd9ca7a756115eabdff2ab281ee9d8c22f44b51d97a6801169d65d90ff16327\n', 'Mike': '7ea29f746dc7abe2893bb4279c06aa1e4443c90c4ea2da75557b548d4ecf6694\n', 'Alice': '65791165c0545089fdd23860a47cb594e81aecf30ceb4013944e2eb20b16a959\n', 'Zach': '69aeb1c2851e1a68538654740c7fccccb8d91c2ee96f5281bfba22443045105c\n', 'Vicky': 'bf8ee9479549dde9721ae599d133574ff8230b3cee81baa4f954880af571aa53\n'}

Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
  • 5
    `dct = {line.split(":")[0]:line.split(":")[1].strip() for line in file} ` – Rakesh Oct 01 '19 at 09:24
  • Possible duplicate of [reading file without newlines in Python](https://stackoverflow.com/questions/12330522/reading-file-without-newlines-in-python) – FObersteiner Oct 01 '19 at 09:26

4 Answers4

1

Try by stripping '\n' from the right side when generating the dictionary:

{line.split(":")[0]:line.split(":")[1].rstrip('\n') for line in file}
yatu
  • 86,083
  • 12
  • 84
  • 139
1

You can insert another generator to avoid splitting twice. It would also be nice to open the file in a context, so that it gets autoclosed.

with open('textfile.txt') as file:
    dct = { k: v for k, v, *_ in (line.rstrip().split(':') for line in file) }
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

Trim the string,

dct = {line.split(":")[0]:line.split(":")[1].strip() for line in file}

This will remove other kinds of whitespace too, which is more than likely what you'd want.

If you just want to remove the last newline, use .rstrip('\n') instead of .strip()

nos
  • 223,662
  • 58
  • 417
  • 506
0

I think, you can directly do this :

dct = dict([i.strip().split(':') for i in file.readlines()])
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56