Counter in a dictionary value

Asked

Viewed 356 times

0

I am a beginner in programming and am doing an exercise in which I need to count the votes of certain numbers according to the number of the player’s shirt. For example, if I type in the program 23, 3 times, the number 23 will have 3 votes. I wonder if there is any way to go adding the number of votes in the key value.

while numero_camisa != 0:
numero_camisa = int(input('Informe o número da camisa do jogador ou zero para sair: '))
if numero_camisa < 0 or numero_camisa > 23:
    print('Número da camisa inválido, favor informar um número entre 1 e 23.')
votos_atletas[numero_camisa] = #acrescentar o número de votos conforme o número da camisa.

My code so far, was like this. Now is the doubt, there is a way to add the number of votes according to what the user is reporting ?

  • This exercise can be found at https://wiki.python.org.br/ExerciciosListas, exercise nº 18.

2 answers

0

You need to access the current dictionary value for the value of numero_camisaand increase that value by 1.

Before you see the answer, try to do it yourself this way. As you open the current value of votes of the player numero_camisa? How do you assign value to a variable?


votos_atletas[numero_camisa] = votos_atletas[numero_camisa] + 1
  • Thank you very much, I had forgotten, I tried to assign the value in every way, but forgot to assign the value key, thank you very much!

  • You’re welcome. Accept the answer if it worked.

0


Python has, in addition to the dictionary structure that can be used, a native structure in the library collections for the solution of this problem: Counter. Just store all the votes in a list:

from collections import Counter

votos = []

while True:
    numero_camisa = int(input('Número da camisa: '))
    if numero_camisa == 0:
        break
    elif 0 < numero_camisa < 23:
        votos.append(numero_camisa)
    else:
        print('Número inválido')


votacao = Counter(votos)

print(votacao)

See working on Repl.it

If the entrance was, for example, [1, 2, 2, 3, 2, 4], the exit would be:

Counter({2: 3, 1: 1, 3: 1, 4: 1})
  • Did not know this, will help me a lot in the studies, thanks for sharing.

Browser other questions tagged

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