onlyf
onlyf

Reputation: 883

Python - File to Dictionary with specific substrings for key value pairs

I have a text file that looks like :

AAAAA123123423452452BBBASDASAS323423423432
BBBBB453453453466123AAAAADDFFG6565656565665

...

I want to create a dictionary out of this, with keys the slices of each line like this :

file.txt :

hash[123123] = "BBBASD"
hash[453453] = "AAAAAD"

I ve written the following try, but it doesnt work so far. Prints nothing :

myhash{}
with open('file.txt') as fi:
    for life in fi:
        key = [line:6:13]
        value = [line:21:27]
        myhash[key] = value

print(myhash) 

Can someone help? Thanks in advance!

Upvotes: 0

Views: 41

Answers (1)

Xavier C.
Xavier C.

Reputation: 1981

You should use:

myhash = {}
with open('file.txt') as fi:
    for line in fi.readlines():
        key = line[5:11]
        value = line[20:26]
        myhash[key] = value

print(myhash) 

You can get more info here about string slicing in Python.

Upvotes: 2

Related Questions