In: Computer Science
How would I create a nested dictionary given a csv file in Python? Say I want to make a dictionary that read
{'country':{'China':'Fit', 'China':'Overweight', 'USA': 'Overweight', 'USA': 'Fit', 'England':'Fit'...}, 'category':{'Asian':'Fit', 'Caucasian': 'Overweight', 'Caucasian':'Overweight', 'Asian': 'Fit', 'Middle Eastern': 'Fit'...}}
given a file that had
country category Weight
China Asian Fit
China Caucasian Overweight
USA Caucasian Overweight
USA Asian Fit
England Middle Eastern Fit...
...
And so on in the file.
# open file
file = open('input.txt', 'r')
data = file.readlines()
# close file
file.close()
# split each line
for i in range(len(data)):
data[i] = data[i].split()
temp = ['', data[i][1], '']
temp[0] = data[i][0]
for j in range(2, len(data[i])-1):
temp[1] += ' '+data[i][j]
temp[2] = data[i][-1]
data[i] = temp
# create dictionary
required_data = {}
# insert data
required_data[data[0][0]] = {}
required_data[data[0][1]] = {}
for i in range(1, len(data)):
# insert country
required_data[data[0][0]][data[i][0]] = data[i][2]
# insert category
required_data[data[0][1]][data[i][1]] = data[i][2]
print(required_data)
.
Screenshot:
.
input:
.
Output:
.
Output doesn't match to your output because in dictionary, every index must match to some single value.
but your dictionary has matched multiple values to same index like,
'China':'Fit', 'China':'Overweight'
This can't happen in a dictionary.