[英]Creating a numbered list from a text file
I'm looking to convert a list of names in a text file into a dictionary, with numbers in front of the names as a list.我正在寻找将文本文件中的名称列表转换为字典,名称前面的数字作为列表。
text file:文本文件:
Adam A
Bob B
Charles C
The text file just has a name every line文本文件每行都有一个名称
Desired results:期望的结果:
{1: 'Adam A', 2: 'Bob B', 3: 'Charles C'}
So far this is my current code到目前为止,这是我当前的代码
numbered_dict = {}
namelist = open("data.txt")
for line in namelist:
a=0
a+=1
numbered_dict[a]=line
and the output is: output 是:
{1: 'Charles C'}
For some reason its only taking the very last name in the list出于某种原因,它只取列表中的最后一个名字
Any help would be much appreciated, thanks!任何帮助将不胜感激,谢谢!
for line in namelist:
a=0
a+=1
numbered_dict[a]=line
Each time through the loop you set a
to 0 and then increase it to 1.每次通过循环时,您将a
设置为 0,然后将其增加到 1。
You have to initialize the variable outside the loop:您必须在循环外初始化变量:
a=0
for line in namelist:
a+=1
numbered_dict[a]=line
As a better tool, however, you can use the dict
constructor and the enumerate
function:但是,作为更好的工具,您可以使用dict
构造函数和enumerate
function:
numbered_dict = dict(enumerate(open("data.txt")))
Try this:尝试这个:
import csv
# Create a dictionary that will contain the file data
dic = {}
# Open the file and read it
with open('data.txt', 'r') as fd:
# contain file in a list
reader = csv.reader(fd)
# Create a counter that will be the key of a line in the file
count = 1
for row in reader:
dic[count] = row[0]
count += 1
print(dic)
You should initialize a=0
just above the loop, not within.您应该在循环上方而不是内部初始化a=0
。 Your code should be你的代码应该是
numbered_dict = {}
namelist = open("data.txt")
a=0
for line in namelist:
a+=1
numbered_dict[a]=line
import ast
with open('data.txt') as file:
data=file.read()
numbered_dict=ast.literal_eval(data)
print(numbered_dict)
output: output:
{1: 'Adam A', 2: 'Bob B', 3: 'Charles C'}
You can read several other methods here:您可以在此处阅读其他几种方法:
https://www.geeksforgeeks.org/how-to-read-dictionary-from-file-in-python/ https://www.geeksforgeeks.org/how-to-read-dictionary-from-file-in-python/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.