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

Question:

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

can anybody 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)

Answer:

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

Well then, 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 for block is executed. It is through him 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 type the first name and press enter . We then received the following message: Altura de fulano: . At this moment, we must type the height of that person and press enter . Then we must type the name and height of the other people.

After typing the last person's name and height – 10th person – and pressing enter , the 2nd for block will be executed. At this time, the highest height and the name(s) of the person(s) who own it will be verified. Then the name(s) of the person(s) with the greatest height is displayed.

Observation

THE PRIORITY FUNCTION OF A REPEATING LOOP – IN THE CASE HERE ONE IS – IS JUST TO REPEAT INTERACTIONS . Well, if you hadn't entered the 2nd STR, only one person who, perhaps, had the greatest height would be displayed. How to insert the 2nd FOR the code will be able to display THE NAME OF ALL THE PERSONS who, by chance, have the maximum height.

So, the use of this 2nd FOR is HIGHLY NECESSARY .

Because if you pay attention to the penultimate print()

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

…refers to the cases of having only one way out – a single person's name – or to more ways out – several people.

Scroll to Top