Adding elements to a dictionary only if the key does not exist

Asked

Viewed 126 times

2

I have to create a function that adds the data of a new student to a dictionary.

Entree:

  • students: dictionary with the students' data
  • name: student name (key)
  • notes: list of a student’s grades (value)

Return:

  • The function should return the dictionary with the modifications made*

Note: If the key already exists in the dictionary, you should return the dictionary without any changes.

This is my code, which returns "already registered", and the value was entered for the first time:

alunos = dict()

def adicionar_aluno ( alunos , nome , notas ):
    alunos[nome]=[notas]
    if nome in alunos:
        return 'já cadastrado'
    else:
        return alunos

nome = input ( 'nome: ' )
notas = float ( input ( 'nota: ' ) )
a=adicionar_aluno(alunos, nome, notas)
print(a)

2 answers

2


This happens because of the order in which things are done (and it could be detected by making a table test).

First you add the student in the dictionary:

alunos[nome]=[notas]

Then you check if this student is in the dictionary:

if nome in alunos:

That is, this if will always be true, because the student you are checking has already been added in the previous row.

What you should do is register the student only if it does not exist in the dictionary (that is, within the else):

def adicionar_aluno ( alunos , nome , notas ):
    if nome in alunos:
        return 'já cadastrado'
    else:
        alunos[nome] = [notas]
        return alunos

Although the requirements say you should always return the dictionary, then just modify the condition to only add the student if it does not exist:

def adicionar_aluno ( alunos , nome , notas ):
    if nome not in alunos:
        alunos[nome] = [notas]
    return alunos

That is, if the student does not exist in the dictionary, add (note not in, that checks if the student is not in the dictionary). If the student already exists, you don’t need to do anything (so you don’t even need the else).

At the end return the dictionary. If it entered the if, he will have the new student. If he has not entered the if, will be returned without modification.


I just found it strange that its function returns a message or the dictionary itself. Perhaps it is better to return True or False, indicating whether or not the student was registered. No need to return the dictionary itself because it is modified within the function:

alunos = dict()

def adicionar_aluno ( alunos , nome , notas ):
    if nome in alunos:
        return False
    else:
        alunos[nome] = [notas]
        return True

nome = input('nome: ')
nota = float(input('nota: ' ))
if adicionar_aluno(alunos, nome, nota):
    print(f'aluno {nome} adicionado')
else:
    print(f'aluno {nome} já cadastrado')
  • 1

    Thank you very much guy, gave a light here on my problem, I’m starting in language and then some things are kind of confusing, obg!

1

Just place the assignment of notes inside the block if and use a not before to check if the student is not registered.

Nor is it necessary else since anyway, the dictionary will be returned. See the code below:

def adicionar_aluno ( alunos, nome, notas ):

    if not nome in alunos:
        alunos[nome] = [notas]
    return alunos

As the function adicionar_aluno changes the dictionary object directly without creating a new dictionary, think it would not be necessary to return the dictionary and yes a value bool as True or False to tell if the dictionary has been modified.

def adicionar_aluno ( alunos, nome, notas ):

    if not nome in alunos:
        alunos[nome] = [notas]
        return True

    return False
  • obg for the attention!

Browser other questions tagged

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