B
B
brrekht2021-11-23 20:42:37
Python
brrekht, 2021-11-23 20:42:37

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


Tried like this:
with open(f'{filename}', 'r') as s:
        data = s.read()
        for i in data:
            if '|' in i:
                result = dict(enumerate(data.split()))
                return result

but it only works:
{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

2 answer(s)
L
LXSTVAYNE, 2021-11-23
@brrekht

data = {}
with open('test.txt') as file:
    for line in file:
        k, v = line.split('|')
        data[k] = v.rstrip()

print(data)

L
LordOftheCode, 2021-11-23
@LordOftheCode

res = {0: 'Foundation|Asimov, Isaac', 1: 'Foundation and Empire|Asimov, Isaac', 2: 'Second Foundation|Asimov, Isaac', 3: 'Dune|Herbert, Frank'}

slv = {res}

print(slv)

try

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question