In Python, a dictionary is a collection that allows us to store data in key-value pairs.
Create a Dictionary
We create dictionaries by placing key:value pairs inside curly brackets {}, separated by commas. For example,
Output
{'United States': 'Washington D.C.', 'Italy': 'Rome', 'England': 'London'}
The country_capitals dictionary has three elements (key-value pairs).
Note: Dictionary keys must be immutable, such as tuples, strings, integers, etc. We cannot use mutable (changeable) objects such as lists as keys.
Tip: We can also use Python's dict() function to create dictionaries.
Python Dictionary Length
We can get the size of a dictionary by using the len() function.
Access Dictionary Items
We can access the value of a dictionary item by placing the key inside square brackets.
Note: We can also use the get() method to access dictionary items.
Change Dictionary Items
Python dictionaries are mutable (changeable). We can change the value of a dictionary element by referring to its key. For example,
Output
{'United States': 'Washington D.C.', 'Italy': 'Rome', 'England': 'London'}
Add Items to a Dictionary
We can add an item to the dictionary by assigning a value to a new key (that does not exist in the dictionary). For example,
Output
{'United States': 'Washington D.C.', 'Italy': 'Rome', 'Germany': 'Berlin'}
Note: We can also use the update method() to add or change dictionary items.
Remove Dictionary Items
We use the del statement to remove an element from the dictionary. For example,
Output
{'Italy': 'Naples'}
Note: We can also use the pop method() to remove an item from the dictionary.
If we need to remove all items from the dictionary at once, we can use the clear() method.
Python Dictionary Methods
Here are some of the commonly used dictionary methods.
| Function | Description |
|---|---|
| pop() | Remove the item with the specified key. |
| update() | Add or change dictionary items. |
| clear() | Remove all the items from the dictionary. |
| keys() | Returns all the dictionary's keys. |
| values() | Returns all the dictionary's values. |
| get() | Returns the value of the specified key. |
| popitem() | Returns the last inserted key and value as a tuple. |
| copy() | Returns a copy of the dictionary. |
Dictionary Membership Test
We can check whether a key exists in a dictionary using the in operator.
Note: The in operator checks whether a key exists; it doesn't check whether a value exists or not.
Iterating Through a Dictionary
A dictionary is an ordered collection of items (starting from Python 3.7). Meaning a dictionary maintains the order of its items.
We can iterate through dictionary keys one by one using a for loop.