2

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.

001
  • 13,291
  • 5
  • 35
  • 66
mustafa789
  • 39
  • 1
  • 4
  • 2
    Read the 1st line and split. Read 2nd line and split. Then: [How do I convert two lists into a dictionary?](https://stackoverflow.com/a/209854) – 001 Dec 29 '21 at 14:13
  • 1
    That's a quite ugly file format definition. Are you sure you can't change the way the file is written? – Thomas Weller Dec 29 '21 at 14:16
  • Why not JSON or an INI like Config file?, There is a parser available for INI formats: https://docs.python.org/3/library/configparser.html – gkns Dec 29 '21 at 14:24
  • 2
    `with open("dict.txt") as f: d = dict(zip(map(int, next(f).split()), next(f).split()))`. – ekhumoro Dec 29 '21 at 14:27

3 Answers3

4

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'}
HIMANSHU PANDEY
  • 684
  • 1
  • 10
  • 22
2

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

    
Mets_CS11
  • 99
  • 1
  • 9
0

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)

rahi
  • 24
  • 4
  • if you do not use d.update and instead of that make assignment then on each iteration it gets overrides. – rahi Jan 02 '22 at 06:10