将列表值分配给字典 python

assign list values to dictionary python

所以我正在处理一组由

组成的字典
{'Summery':["00","01","02"],'Location':["03","04"],'Name':["05"]}

现在每个数字都与每行的字数相关

在我的文本文件中,行的格式是这样的

Fun Reading Afterschool 50°N 50°E Library
Education Learning Study 51°N 51°E School
Exercise Play Social 52°N 52°E Playground

如何将 input.txt 转换为所需的输出:

output.txt

{'Summery':["Fun","Reading","Aftershchool"],'Location':["50°N","50°E"],'Name':["Library"]}
{'Summery':["Education","Learning","Study"],'Location':["51°N","51°E"],'Name':["School"]}
{'Summery':["Exercise","Play","Social"],'Location':["52°N","52°E"],'Name':["Playground"]}

到目前为止我有

file = open("input.txt", 'r')
lines = file.readlines()

list_word = []
for l in lines:
    list_word.append(l.split(" "))

my_list = [line.split(' , ')for line in open ("test")]

string1="".join(map(str,my_list))
print(string1)

new_main = open("output.txt", 'w')
new_main.write(string1)
new_main.close()

打印并创建 output.txt

['Fun Reading Afterschool 50°N 50°E Library\n']['Education Learning Study 51°N 51°E School\n']['Exercise Play Social 52°N 52°E Playground']

假设summary总是3个词,location 2和name 1个词(每个词用一个空格隔开),你可以根据索引取想要的词。

for string in string1:
    splits = string.split(" ")
    
    summary = splits[0:3]
    location = splits[3:5]
    name = splits[5:6]
    
    print(f"Summary: {summary}, location: {location}, name: {name}")