Dictionaries
Swipe to show menu
A dictionary stores data as key-value pairs, letting you access values by key instead of position. It's useful for structured data, like a user's name, age, or preferences.
Keys must be unique and immutable (strings, numbers, or tuples). Values can be any type β strings, numbers, lists, or even other dictionaries.
Creating a Dictionary
Dictionaries are defined with curly braces, using key: value pairs separated by commas.
Example: person = {"name": "Alice", "age": 30}
Here "name" maps to "Alice", and "age" maps to 30.
Accessing and Updating Values
Use square brackets to access a value: person["name"].
- If the key exists, it returns the value;
- If not, Python raises a
KeyError.
With .get(), missing keys return None or a fallback: person.get("nickname", "N/A").
Update values by reassigning: person["age"] = 31.
Adding and Removing Items
To add a new key-value pair, just assign to a new key β Python will insert it: person["city"] = "London".
To remove a key, you can use del, as del person["age"]. Or use .pop("key") if you want to remove and return the value.
Keys and Values
Dictionaries come with handy built-in methods:
.keys()returns a list-like view of all the keys;.values()returns all the values;.items()returns pairs as tuples β useful for looping.
These are especially useful when you're iterating or analyzing a dictionary.
Summary
- A dictionary holds key-value pairs, where keys are unique and used to look things up;
- Keys must be immutable (like strings or numbers), values can be any type;
- You can add, update, delete, and safely retrieve values using
.get(); - Use
.keys(),.values(), and.items()to work with dictionary content efficiently.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat