Dictionary error

Asked

Viewed 82 times

3

What’s wrong with this dictionary?

Dados = {'Alunos': {
    {'Nome': 'Jon', 'Notas':[8,9,6]},
    {'Nome': 'Giglio', 'Notas':[7,6,5]},
    {'Nome': 'Antony', 'Notas':[5,6,9]}
    }
}

for nome, info in Dados.items():
    print(nome, info)

Error returned:

Typeerror: unhashable type: 'Dict'

  • I need to create one more FOR inside the first FOR ??

  • 1

    Dictionary cannot be key to another.

  • 1

    As in my answer? Or otherwise?

2 answers

9

A dicionário can’t be chave from another dictionary because the key must be a objeto imutável, moreover it is more logical to define students as a list in the following way:

dados = {'Alunos': [
    {'Nome': 'Jon', 'Notas':[8,9,6]},
    {'Nome': 'Giglio', 'Notas':[7,6,5]},
    {'Nome': 'Antony', 'Notas':[5,6,9]}
]}

for aluno in dados['Alunos']:
    for nome, notas in aluno.items():
        ...

1

In fact, what you intend to create is a list of students within a dictionary. There was a small error in your code.

You have the dictionary Dados with the item Alunos that keeps a list of students inside it, and each student is formed by a dictionary with the keys Nome and Notas.

So logic is a list of dictionaries within another dictionary:

Dados = {'Alunos': [ # o erro aconteceu neste ponto quanto você colocou { ao invés de [
    {'Nome': 'Jon', 'Notas':[8,9,6]},    # primeiro aluno da lista
    {'Nome': 'Giglio', 'Notas':[7,6,5]}, # segundo aluno da lista
    {'Nome': 'Antony', 'Notas':[5,6,9]}  # terceiro aluno da lista
]}

To scroll through students and display their data, you first need to enter the key Alunos dictionary Dados:

for aluno in Dados['Alunos']: # para cada aluno
    print(aluno['Nome'], aluno['Notas']) # mostre o nome e nota

Browser other questions tagged

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