Populating a dictionary of dictionaries through a for loop

Asked

Viewed 119 times

0

I’m trying to create a loop to add information in a dictionary. The most external key of the dictionary will be the name of a course, and the value will be another dictionary, there will be 6 keys, referring to the form of admission to the college, and the value of these keys will be the average of the monthly fee for that group (course and form of entry)

entrada = {}
cursos = {}

for curso in toledo.curso.unique():
    materia = toledo[toledo['curso'] == curso]
    for forma_de_entrada in materia.forma_de_entrada.unique():
        media = materia[materia['forma_de_entrada'] == forma_de_entrada].valor_liquido_da_mensalidade.mean()
        entrada[forma_de_entrada] = media
    cursos[curso] = entrada

I even got the dictionary popular, but the average values are the same for all courses. I also tried to clear the input dictionary after I added it to the dictionary courses, but also not the right one.

  • 2

    No one could help you on this issue because the code is incomplete - looking only at the code you put who is looking has to guess that "Toled" is a pandas dataframe - it is important to put something "mimically reproducible" in the code - including a line that creates a minimum dataframe with the data examples you have

1 answer

0

I managed to do otherwise, instead of making a dictionary of other dictionaries popular, I populated it with groupby objects.

dic = {}

for curso in toledo.curso.unique():
    media_curso = toledo[(toledo['curso'] == curso) & (toledo['status'] == 'matriculado')].groupby('forma_de_entrada')\
                  .valor_liquido_da_mensalidade.mean()
    dic[curso] = media_curso

Although I did, I was wondering if it’s possible to do this with a dictionary of dictionaries, and if there’s a better way to solve this.

Thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.