从 txt 文件创建字典。每行一个字母。键是字母,值应该是循环的迭代

Create dictionary out of txt file. One alphabet letter per row. Key is letter and value should be iteration of the loop

我有问题.. 我有一个如下所示的 txt 文件:

a
b
c
d

每行一个字母,每行没有两个值,因此无需拆分..

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)

但我每行应该只有 1 个值...我认为迭代应该是第二个值..但我卡住了并且累了..有什么想法吗?

您可以使用 enumerate() 遍历行。另外,不要使用 dict 作为变量名(它遮蔽了 Python built-in):

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

print(dct)

打印:

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