Dictionaries (records) · Dicionários (registros)
Store data by name
- A dictionary stores values under names called keys.
- Write pairs inside braces:
{"name": "Sam", "age": 15}. - Each key is unique and points to one value.
Armazenar dados por nome
- Um dicionário armazena valores sob nomes chamados chaves.
- Escreva pares entre chaves:
{"name": "Sam", "age": 15}. - Cada chave é única e aponta para um único valor.
Get and set values
- Read a value with its key:
person["name"]. - Add or change a value the same way:
person["age"] = 16. - A list uses a number index; a dictionary uses a key.
Obter e definir valores
- Leia um valor com sua chave:
person["name"]. - Adicione ou altere um valor da mesma forma:
person["age"] = 16. - Uma lista usa um índice numérico; um dicionário usa uma chave.
ages = {"Sam": 12, "Mia": 15}
print(ages["Sam"])
ages["Leo"] = 9
print(ages)
A dictionary as a record
- A record groups related facts about one thing.
- A dictionary is a neat way to hold a record.
- Each key is a field, like
nameorgrade.
Um dicionário como registro
- Um registro agrupa fatos relacionados sobre uma coisa.
- Um dicionário é uma forma organizada de guardar um registro.
- Cada chave é um campo, como
nameougrade.
pupil = {"name": "Ada", "grade": "A"}
print(pupil["name"])
print(pupil["grade"])
Check and loop
"name" in personisTrueif that key exists.for key in person:visits each key in turn.person.get("x", 0)returns a default if the key is missing.
Verificar e iterar
"name" in personéTruese essa chave existir.for key in person:visita cada chave sequencialmente.person.get("x", 0)retorna um padrão se a chave estiver ausente.
menu = {"tea": 2, "cake": 5}
for item in menu:
print(item, menu[item])
print("tea" in menu)
In Cambridge pseudocode
- A dictionary models the exam's
TYPErecord; each key is a field reached with a dot.
Em pseudocódigo do Cambridge
- Um dicionário modela o
TYPEregistro da prova; cada chave é um campo acessado com ponto.
TYPE Student
DECLARE Name : STRING
DECLARE Age : INTEGER
ENDTYPE
DECLARE Pupil : Student
Pupil.Name ← "Sam"
Pupil.Age ← 15
Common mistakes
- Read a value by its key:
d["name"]; a missing key raises a KeyError. - Keys are unique — assigning the same key again overwrites the value.
- Use
d.get(key)when the key might be missing.
Erros comuns
- Leia um valor pela sua chave:
d["name"]; uma chave ausente levanta KeyError. - Chaves são únicas — atribuir a mesma chave novamente sobrescreve o valor.
- Use
d.get(key)quando a chave possa estar ausente.
Now you try
- Build or update a dictionary in each task.
- Press Check answer to test your code.
Agora você tenta
- Construa ou atualize um dicionário em cada tarefa.
- Clique em Check answer para testar seu código.
Look up by key · Consultar por chave
A dictionary jumps straight to the value for a key — no scanning. · Um dicionário vai direto ao valor de uma chave — sem varrer.
Create a dictionary book with two keys: title set to "Python" and · e pages set to 200. · Crie um dicionário book com duas chaves: title definido como "Python" e pages definido como 200.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
The dictionary student already has name and · e score. Change score to · até 85, and add a new key passed set to True. · O dicionário student já tem name e score. Mude score para 85 e adicione uma nova chave passed definida como True.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Loop over the dictionary prices and add up its values. Store the total in total (the answer is 10). · Percorra o dicionário prices e some seus valores. Armazene o total em total (a resposta é 10).
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write count_words(text) that returns · decrescentes a dictionary: each word of text (split on spaces) mapped to how many times it appears. count_words("the cat and the hat") gives {"the": 2, "cat": 1, "and": 1, "hat": 1}. · Escreva count_words(text) que retorne um dicionário: cada palavra de text (separada por espaços) mapeada para quantas vezes aparece. count_words("the cat and the hat") dá {"the": 2, "cat": 1, "and": 1, "hat": 1}.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.