简体   繁体   中英

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'}. 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'}

You can't have a dictonary where multiple keys are the same, in your example I would go with an array.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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