I have a text file with this data
JavaScript
x
5
1
1, Jane Doe, 1991
2
2, Sam Smith, 1982
3
3, John Sung, 1965
4
4, Tony Tembo, 1977
5
I have something like this but it only works if you have the ID and name alone
JavaScript
1
6
1
names = {}
2
with open("dict.txt") as f:
3
for line in f:
4
(key, val) = line.strip().split(',')
5
names[int(key)] = val
6
print (d) Can I create a dictionary from this file that would look like this:
JavaScript
1
2
1
{1: [Jane Doe, 1991], 2: [Sam Smith, 1982] }
2
Advertisement
Answer
This is a bit more simple.
JavaScript
1
13
13
1
d = {} # this is the dictonary
2
file = open("data.txt") # open file
3
for line in file:
4
s = line.split() # split line
5
# get data individually
6
key = s[0]
7
fullname = s[1] + ' ' + s[2]
8
year = s[3]
9
# append to dictionary
10
d[key] = [fullname, year]
11
# print
12
print(d)
13
hope this works