简体   繁体   English

如何将文本文件转换为字典?

[英]How to convert a text file into dictionary?

From a file, I am supposed to return a dictionary where each key is a person's name, and each value is a list with three elements in this order: the person's gender, the person's age and the person's height.从一个文件中,我应该返回一个字典,其中每个键都是一个人的名字,每个值都是一个列表,其中包含三个元素:人的性别、人的年龄和人的身高。

For example, if my file "file.txt" has two lines like this:例如,如果我的文件“file.txt”有如下两行:

Peter, male, 18, 180彼得,男性,18 岁,180 岁
Andrew, male, 40, 175安德鲁,男性,40 岁,175 岁

Then the dictionary returned by this function would be:那么这个函数返回的字典将是:

{"Peter": ["male", 18, 180], "Andrew": ["male", 40, 175]} {"Peter": ["male", 18, 180], "Andrew": ["male", 40, 175]}

I tried:我试过:

d={}
L=[]
f= open("items.txt","r")
for line in f:
    (key, val) = line.split(",",1)
    value= val.split(",")
    L.append(value)
    d[key] = L
return d
f.close()    

And it returns: {'Peter': [[' male', ' 18', ' 180 \\n'], [' male', ' 40', ' 175']], 'Andrew': [[' male', ' 18', ' 180 \\n'], [' male', ' 40', ' 175']]}它返回: {'Peter': [['male', '18', '180 \\n'], ['male', '40', '175']], 'Andrew': [['male' , '18', '180 \\n'], ['男', '40', '175']]}

Your code is using the same L variable, resulting in an accumulation effect you don't want.您的代码使用相同的L变量,从而导致您不想要的累积效应。 Besides, it doesn't convert integers strings to integers, and doesn't remove end of line chars for the last item.此外,它不会将整数字符串转换为整数,也不会删除最后一项的行尾字符。

Other small mistake is returning the value and closing the file afterwards (this close statement isn't reached, so the file is closed whenever python decides. A with context manager is always better in those cases)另一个小错误是返回值并在之后关闭文件(未达到此 close 语句,因此每当 python 决定时关闭文件。在这些情况下, with上下文管理器总是更好)

if f is your file handle (or a list of lines), this one-liner does the job:如果f是您的文件句柄(或行列表),则此单行程序可以完成以下工作:

f="""a,b,1,2
apple,banana,3,4""".splitlines()

d = {t[0]:[int(x) if x.isdigit() else x.rstrip() for x in t[1:]] for t in (l.split(",") for l in f)}

it splits according to comma, then builds a dict comprehension, using first item as key and other items as values, using rstrip to handle the newline of the last field.它根据逗号进行拆分,然后构建字典理解,使用第一项作为键,其他项作为值,使用rstrip处理最后一个字段的换行符。

The extra string to integer conversion uses isdigit so it's not perfect.额外的字符串到整数转换使用isdigit所以它并不完美。 (doesn't work for negative numbers). (不适用于负数)。 Can be replaced by an aux function.可以用辅助功能代替。

result:结果:

{'apple': ['banana', 3, 4], 'a': ['b', 1, 2]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM