How to create a dictionary of lists from each row of a text file?

Tags: ,



I have a text file with this data

1, Jane Doe, 1991
2, Sam Smith, 1982
3, John Sung, 1965
4, Tony Tembo, 1977

I have something like this but it only works if you have the ID and name alone

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

print (d) Can I create a dictionary from this file that would look like this:

{1: [Jane Doe, 1991], 2: [Sam Smith, 1982]...}

Answer

This is a bit more simple.

d = {} # this is the dictonary
file = open("data.txt") # open file
for line in file:
    s = line.split() # split line
    # get data individually
    key = s[0] 
    fullname = s[1] + ' ' + s[2]
    year = s[3]
    # append to dictionary
    d[key] = [fullname, year]
# print
print(d)

hope this works



Source: stackoverflow