我正在尝试编写一个程序,该程序采用这种格式的带有行的文本文件,并将其转换为dict。
John
Doe
Bob
Cape
我需要第一行是关键字,下一行是空白字典的值。
这是我到目前为止所尝试的,我真的不确定如何为每个名字和姓氏获得一行作为关键字,下一行作为值。非常感谢。
people = {}
with open('names.txt', 'r') as data:
data = data.readlines()
for line in data:
line = line.strip()
people[line] = ' '
print(people)
您可以在范围内循环,步长为2:
people = {}
with open('names.txt', 'r') as file:
# `read().splitlines()` removes the new line characters
# from the ends of the lines in an efficient way
lines = file.read().splitlines()
for i in range(0, len(lines), 2):
people[lines[i]] = lines[i + 1]
print(people)
输出:
{'John': 'Doe', 'Bob': 'Cape'}
请尝试此处。