Dictionaries
Think about a real dictionary — each word has a definition. In Python, a dictionary works the same way: it stores data as key-value pairs, where each key maps to a value.
You’d use a dictionary when your data has labels. Instead of a list where you track things by position, a dictionary lets you look things up by name.
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}Here, "name", "age", and "city" are keys. "Alice", 30, and "New York" are their values.
Creating a dictionary
Put key-value pairs inside curly braces {}. Separate each pair with a comma, and use a colon : between each key and value.
Keys must be unique — if you use the same key twice, the second value overwrites the first:
person = {
"name": "Alice",
"name": "Aly" # overwrites "Alice"
}
print(person) # Output: {'name': 'Aly'}Values can be any type — strings, numbers, booleans, lists, even other dictionaries.
Try it out
main.py
Output
Last updated on