The dictionaries allow us to identify each element by a key
, opposed to lists where there are only values and indexes. To define a dictionary, the list of values is enclosed in curly braces. Key and value pairs are separated by commas, and keys are separated from values by colons:
{
"key": value,
"other_key": other_value,
...
}
list = ["a", "b", "c"]
dictionary = { "one": "a", "two": "b", "three": "c" }
person = { "name": "Juan", "lastname": "Contreras" }
print(person["name"]) # Output: "Juan"
person["age"] = 22
print(person) # Output: { "name": "Juan", "lastname": "Contreras", "age": 22 }
spanish_translations = { "dog": "perro", "house": "casa", "cat": "gato" }
for key in spanish_translations:
print(key) # <-- Output: "dog", "house", "cat"
print(spanish_translations[key]) # <-- Output: "perro", "casa", "gato"
- Programmatically add the following translations to the
spanish_translations
dictionary:
love -> amor
code -> codigo
smart -> inteligente
{'dog': 'perro', 'house': 'casa', 'cat': 'gato', 'love': 'amor', 'code': 'codigo', 'smart': 'inteligente'}