简体   繁体   English

如何使用相同的键将 python 中的文本文件转换为字典

[英]how to convert text file to dictionary in python wtih same key

I wonder how can i convert this text file:我想知道如何转换这个文本文件:

Score 2
Score 1
Score 3
Score 21 

to a dictionary which would look like this: {'Score': '2', 'Score': '1', 'Score': '3', 'Score': '21'}.到一个看起来像这样的字典:{'Score':'2','Score':'1','Score':'3','Score':'21'}。 Because of the fact that the key name is the same this code:由于键名相同,因此此代码:

a_dictionary = {}
a_file = open("score.txt")
for line in a_file:
    key, value = line.split()


    a_dictionary[key] = value

print(a_dictionary)

prints only the last dict {'Score': '21'}仅打印最后一个字典{'Score': '21'}

You can't have a dictonary where multiple keys are the same, in your example I would go with an array.您不能拥有多个键相同的字典,在您的示例中,我将使用数组 go 。

a_array = []
for line in a_file:
    a_array.append(line.split(" ")[1])

print(str(a_array))

Then you can access the respective line with a_array[line_number]然后您可以使用a_array[line_number]访问相应的行

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

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