Home > Net >  assign list values to dictionary python
assign list values to dictionary python

Time:11-18

So I am working with a set of dictionarys consisting of

{'Summery':["00","01","02"],'Location':["03","04"],'Name':["05"]}

now each number correlates to the word count on each line

And in the text file I have, the lines that are formatted as so

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

How Can I convert the input.txt to the desired output:

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"]}

so far I have

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()

which prints and creates 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']

CodePudding user response:

Assuming the summary is always 3 words, the location 2 and the name 1 word (each seperated by one whitespace), you can take the wanted words based on their indices.

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}")
  • Related