Dictionaries
What Is a Dictionary?
A dictionary is a built-in Python data type used to store key-value pairs. Unlike lists or tuples (which store values by position/index), dictionaries allow you to store data in a way where each value is linked to a unique key. This makes lookup, insertion, and deletion of values fast and efficient.
Think of it like a real-life dictionary: you look up a word (key) and find its definition (value).
Syntax & Structure
The basic structure of a Python dictionary is:
- Keys must be unique and immutable (strings, numbers, or tuples).
- Values can be of any data type, including other dictionaries or lists.
Accessing & Modifying Values
To get a value:
To modify a value:
To add a new key-value pair:
To remove a key:
To safely access a key without an error:
Useful Dictionary Methods
Method | Description |
---|---|
.get(key) |
Returns the value for the key if it exists, else returns None or default value. |
.keys() |
Returns a view of all keys in the dictionary. |
.values() |
Returns a view of all values. |
.items() |
Returns key-value pairs as tuples. |
.update() |
Adds or updates key-value pairs. |
.pop(key) |
Removes the item with the specified key and returns its value. |