Home > database >  Create dictionary out of txt file. One alphabet letter per row. Key is letter and value should be it
Create dictionary out of txt file. One alphabet letter per row. Key is letter and value should be it

Time:05-21

i got a problem.. I have a txt file that looks like this:

a
b
c
d

One letter per row, there is not two values per row, so nothing to split..

This code works, if I add a second value in my alphabetFile.
dict = {}
with open("alphabet.txt") as alphabetFile:
    for line in alphabetFile:
        (key, val) = line.split()
        dict[int(key)] = val

print(dict)

But I should only have 1 value per row... Im thinking the iteration should be the second value.. but im stuck and tired.. any ideas?

CodePudding user response:

You can use enumerate() to iterate over lines. Also, don't use dict as name of variable (it shadows Python built-in):

dct = {}
with open("alphabet.txt") as alphabetFile:
    for iteration, line in enumerate(alphabetFile, 1):
        dct[line.strip()] = iteration

print(dct)

Prints:

{'a': 1, 'b': 2, 'c': 3, 'd': 4}
  • Related