fiona
fiona

Reputation: 89

Creating a dictionary inside another dictionary

Given the following data how can I create a dictionary where the keys are the names of the students, and the values are dictionaries where the key is the test and it´s value is the grade they got in it.

grades =  [
   ['Students', 'Test 1', 'Test 2', 'Test 3'],
   ['Tomas', '100', '90', '80'],
   ['Marcos', '88', '99', '111'],
   ['Flavia', '45', '56', '67'],
   ['Ramon', '59', '61', '67'],
   ['Ursula', '73', '79', '83'],
   ['Federico', '89', '97', '101']
] 

I tried doing this, but I don´t know why it´s not showing the grades correctly.

notas_dict={}

def dic(etiquets, notas):
   for i in range(len(etiquets)):
       notas_dict[etiquets[i]]=int(notas[i])
   return notas_dict
dic(['Test 1','Test 2', 'Test 3'], ['100','80','90'] )

dic_final={}

for line in grades[1:]:
   line_grades=[int(element) for element in line[1:]]
   dic_final[line[0]]=dic(['Test 1','Test 2', 'Test 3'], line_grades)
print(dic_final)

The output should be :



{'Tomas': {'Test 1': 100, 'Test 2': 90, 'Test 3': 80}, 'Marcos': {'Test 1': 88, 'Test 2': 99, 'Test 3': 111}, 'Flavia': {'Test 1': 45, 'Test 2': 56, 'Test 3': 67}, 'Ramon': {'Test 1': 59, 'Test 2': 61, 'Test 3': 67}, 'Ursula': {'Test 1': 73, 'Test 2': 79, 'Test 3': 83}, 'Federico': {'Test 1': 89, 'Test 2': 97, 'Test 3': 101}}

Upvotes: 1

Views: 44

Answers (2)

create a dataframe then use to_records to create a list of tuples where each tuple is a row. You can then slice the tuple by index.

 grades =  [
   ['Students', 'Test 1', 'Test 2', 'Test 3'],
   ['Tomas', '100', '90', '80'],
   ['Marcos', '88', '99', '111'],
   ['Flavia', '45', '56', '67'],
   ['Ramon', '59', '61', '67'],
  ['Ursula', '73', '79', '83'],
  ['Federico', '89', '97', '101']
 ] 

 Columns=grades[0]
 df=pd.DataFrame(columns=Columns)
 for i in range(1, len(grades)):
     df_length = len(df)
     df.loc[df_length] = grades[i]

 print(df.to_records())

output:

 [(0, 'Tomas', '100', '90', '80') (1, 'Marcos', '88', '99', '111')
 (2, 'Flavia', '45', '56', '67') (3, 'Ramon', '59', '61', '67')
 (4, 'Ursula', '73', '79', '83') (5, 'Federico', '89', '97', '101')]

or

 dict=df.T.to_dict()
 for k,v in dict.items():
     print(k,v['Students'],v['Test1'],v['Test2'],v['Test3'])

Upvotes: 0

Hamza
Hamza

Reputation: 6025

You can use:

{i[0]:dict(zip(grades[0][1:],i[1:])) for i in grades[1:]}

results in:

{'Tomas': {'Test 1': '100', 'Test 2': '90', 'Test 3': '80'},
 'Marcos': {'Test 1': '88', 'Test 2': '99', 'Test 3': '111'},
 'Flavia': {'Test 1': '45', 'Test 2': '56', 'Test 3': '67'},
 'Ramon': {'Test 1': '59', 'Test 2': '61', 'Test 3': '67'},
 'Ursula': {'Test 1': '73', 'Test 2': '79', 'Test 3': '83'},
 'Federico': {'Test 1': '89', 'Test 2': '97', 'Test 3': '101'}}

If you want to get grades as int:

{i[0]:dict(zip(grades[0][1:],list(map(int,i[1:])))) for i in grades[1:]}

Upvotes: 1

Related Questions