The . append() is not working in my dictionary - Python

Asked

Viewed 52 times

-3

Hello, my problem is this: I have a dictionary called People: pessoas = {} that allows me to register the name and age of the person. I made a input asking how many people the user would like to register: quantidade = int(input("Quantas pessoas serão cadastradas? ")).
After that he executes a for: for a in range(0, quantidade):.
So far so good... I ask the name and age of the person to after that I make a .append() in my dictionary and it returns me the following error:

AttributeError: 'dict' object has no attribute 'append'

I really don’t understand why the mistake. Can anyone explain?
The complete code:

pessoas = {}

quantidade = int(input("Quantas pessoas serão cadastradas? "))

for a in range(0, quantidade):
    nome = input(f"Digite o nome da pessoa {a + 1}: ")
    idade = input(f"Digite a idade de {nome}: ")
    pessoas.append(nome)
    pessoas.append(idade)

1 answer

2


Python dictionaries do not have .append: they always keep a key and a value, and this is independent of the insertion order - Given the key (in this case, the "name"), it will always take the same time to return the corresponding value ("age"):

pessoas = {}

quantidade = int(input("Quantas pessoas serão cadastradas? "))

for a in range(0, quantidade):
    nome = input(f"Digite o nome da pessoa {a + 1}: ")
    idade = input(f"Digite a idade de {nome}: ")
    pessoas[nome] = idade

print(pessoas)

To learn, it’s important to do it this way. When creating more complex programs it is important that a data that can be repeated (the name), is not the key of the dictionary: the values that comes last go over-write the first ones - but this you take with time - for example, in this case it may be better to have a "list of dictionaries", in which each dictionary has the key "name" and "age" separated. But to get there, you need to understand dictionaries first.

Browser other questions tagged

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