Home > Net >  How to make a dictionary from a txt file?
How to make a dictionary from a txt file?

Time:12-30

Assuming a following text file (dict.txt) has

1    2    3
aaa  bbb  ccc

the dictionary should be {1: aaa, 2: bbb, 3: ccc} like this

I did:

d = {}
with open("dict.txt") as f:
for line in f:
    (key, val) = line.split()
    d[int(key)] = val

print (d)

but it didn't work. I think it is because of the structure of txt file.

CodePudding user response:

The data which you want to be keys are in first line, and all the data which you want to be as values are in second line.
So, do something like this:

with open(r"dict.txt") as f: data = f.readlines() # Read 'list' of all lines

keys = list(map(int, data[0].split()))            # Data from first line
values = data[1].split()                          # Data from second line

d = dict(zip(keys, values))                       # Zip them and make dictionary
print(d)                                          # {1: 'aaa', 2: 'bbb', 3: 'ccc'}

CodePudding user response:

Updated answer based on OP edit:

#Initialize dict
d = {}

#Read in file by newline splits & ignore blank lines
fobj = open("dict.txt","r")
lines = fobj.read().split("\n")
lines = [l for l in line if not l.strip() == ""]
fobj.close()

#Get first line (keys)
key_list = lines[0].split()

#Convert keys to integers
key_list = list(map(int,key_list))

#Get second line (values)
val_list = lines[1].split()

#Store in dict going through zipped lists
for k,v in zip(key_list,val_list):
    d[k] = v

    

CodePudding user response:

First create separate list for keys and values, with condition like :

    if (idx % 2) == 0:
        keys = line.split()
        values = lines[idx   1].split()

then combine both the lists

d = {}

# Get all lines in list
with open("dict.txt") as f:
    lines = f.readlines()

for idx, line in enumerate(lines):
    if (idx % 2) == 0:
        # Get the key list
        keys = line.split()

        # Get the value list
        values = lines[idx   1].split()

        # Combine both the lists in dictionary
        d.update({ keys[i] : values[i] for i in range(len(keys))})
print (d)

  • Related