How to access the key, by value, in python dictionary?

Asked

Viewed 351 times

3

When filling in the name of 10 people and their respective heights, I need to show on the screen the name of the tallest person. However, I can only get the highest value.

Could someone help me?

people = {}
count = 1
while count <= 2:
    name = str(input('Name: ').strip().title())
    while True:
        try:
            people[name] = float(input('Height: '))
            if type(people[name]) == float:
               break
        except ValueError:
            print('Numbers. Try again.')
    count += 1

print(people)
  • 1

    Searching the Stack Overflow I found a question that has the answer for what you need, follow link: https://answall.com/questions/382490/python-maior-valor-de-um-dicion%C3%A1rio-por-chave

  • Just a detail, in doing float(input(...)), the result is already a float, then you don’t need to check if the type of the variable is float. If a valid number is not entered, it launches the ValueError and the code falls right into except, so this one if it’s unnecessary, you could call the break direct: https://ideone.com/7Ah4Ap

3 answers

4

From what I understand, you want to implement a script that is able to mount a dicionário containing nome and altura of 10 people and then display the name of the tallest person.

Well, you can use the following script:

# Montando um dicionário com nome e altura de 10 pessoas.
people = dict()
for c in range(1, 11):
    n = input(f'{c}º Nome: ').strip().title()
    a = float(input(f'Altura de {n}: '))
    people.update({n: a})

# Verificando a maior altura.
maior = people[max(people, key=people.get)]
print('\033[32mPessoa(s) de maior(es) altura(s):')
for n, a in people.items():
    if a == maior:
        print(f'{n}')

Note that when we run this script the 1st block for. It is through it that the respective dictionary will be assembled.

So when we run the script we get the following message: 1º Nome: . At this point we must enter the first name and press enter. Then we received the following message: Altura de fulano: . Right now we should type the height of the said guy and press enter. Next we must enter the name and height of other people.

After typing name and height of the last person - 10th person - and pressing enter, the 2nd block for. At this time, the highest height and the name(s) of the(s) person(s) who owns it shall be verified. The name(s) of the highest person(s) (s) is displayed next.

Observing

THE PRIORITY FUNCTION OF A LOOP OF REPETITION - IN THIS CASE FOR - IS TO REPEAT INTERACTIONS. Well, if you hadn’t inserted the 2nd FOR only one person would be shown who, perhaps, had the highest height. How to insert the 2nd FOR the code will be able to display THE NAMES OF ALL PEOPLE which may have the maximum height.

So the use of this 2nd FOR and HIGHLY NEEDED.

'Cause if you pay attention to penultimate print()...

print('\033[32mPessoa(s) de maior(es) altura(s):')

...refers to cases where there is only one way out - one person’s name - or more exits - several people.

  • I get it. Thank you very much!

  • 1

    You took a turn in your reply - the max with Kye already name the biggest person, and then just use the dictionary - it is completely unnecessary for final.: name_maiior = max(people, key=people.get); maior_altura = people[name_maior] `

  • @jsbueno I think that the for at the end is interesting if you have a tie (more than one person of equal height)

  • 1

    @hkotsubo - ok, for a Feature more than "what is the highest height" - but this goes over and does not answer "how to access the key by the value" (which is the question) - the best would be to explain "here is the key - but as there can be repetitions of the value, we do more this ... "

  • 2

    @Solkarped - nice you want to show the colored text with ANSI Quence - but there are two cool things to keep in mind: (1) is not very readable or keep having crazy sequences of characters in each print - you can put the sequence to change color in a variable and then use prints like print(f"{VERMELHO} Pessoa(s) de maior(es) altura(s): {NORMAL} )" . Another thing: these sequences don’t work on Windows by default, so it’s nice to mention this.

  • 1

    @jsbueno I agree, it was lacking to put an explanation of this for...

  • 1

    @hkotsubo, explained in detail uso of 2º for. Another thing, like uma pessoa is a subset of várias pessoa, then my answer is sufficient to answer this question.

  • @jsbueno, as for coloração of the answer, I will accept your opinion.

Show 3 more comments

3

Here is another solution that deals with the situation where there are two people of maximum height in the dictionary:

pessoas = {
    "João": 1.71, 
    "Maria": 1.69,
    "Alberto": 1.75,
    "Joana": 1.70, 
    "Pedro": 1.75
}

mais_altas = [pessoa for pessoa, altura in pessoas.items() if 
              altura == max(pessoas.values())]

mais_altas is a list of all the names of people whose height is highest in the dictionary pessoas.

The syntax used in the last line is called list comprehension, which is a simpler way to write a for loop. Here is the equivalent version of the same for loop, "in full":

mais_altas = []
maior_altura = max(pessoas.values())  # encontra maior altura nos valores
for pessoa, altura in pessoas.items():  # itera sobre pares chave-valor
    if altura == maior_altura:  # quando a altura da pessoa for a maior / uma das maiores:
        mais_altas.append(pessoa)
  • 1

    Too simple! Thank you for helping! In fact, I joined the list comprehensions today, it was great to learn a little about the class today, with this answer.

  • Great, glad I could help :-)

1

You can do the same that answer (mentioned in the commentary):

print(max(people, key=people.get))

or if you prefer, go straight through the keys of the dictionary and compare their values:

names = list(people.keys())
if len(names) > 0:
  # inicia o primeiro nome como sendo o maior
  taller = names[0]

  # percorre todos os nomes a partir do segundo
  for name in names[1:]:
    if people.get(name, 0) > people.get(taller, 0):
      taller = name

  print(taller)
else:
  print('no one')
  • Thank you very much!

Browser other questions tagged

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