Answer the question
In order to leave comments, you need to log in
How to convert text from file to dictionary?
The file contains the text:
Foundation|Asimov, Isaac
Foundation and Empire|Asimov, Isaac
Second Foundation|Asimov, Isaac
We need to bring this to the form:
{'Foundation': 'Asimov, Isaac', 'Foundation and Empire': 'Asimov, Isaac', 'Second Foundation': 'Asimov, Isaac'}
with open(f'{filename}', 'r') as s:
data = s.read()
for i in data:
if '|' in i:
result = dict(enumerate(data.split()))
return result
{0: 'Foundation|Asimov, Isaac', 1: 'Foundation and Empire|Asimov, Isaac', 2: 'Second Foundation|Asimov, Isaac', 3: 'Dune|Herbert, Frank'}
Answer the question
In order to leave comments, you need to log in
data = {}
with open('test.txt') as file:
for line in file:
k, v = line.split('|')
data[k] = v.rstrip()
print(data)
res = {0: 'Foundation|Asimov, Isaac', 1: 'Foundation and Empire|Asimov, Isaac', 2: 'Second Foundation|Asimov, Isaac', 3: 'Dune|Herbert, Frank'}
slv = {res}
print(slv)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question