Dictionaries
In this lecture, you'll learn everything about Python dictionaries; how they are created, accessing, adding, removing elements from them and various built-in methods.
Python dictionary is an unordered collection of items. Each item of a dictionary has a key/value pair
.
Dictionaries are optimized to retrieve values when the key is known.
Creating Python Dictionary
Creating a dictionary is as simple as placing items inside curly braces {}
separated by commas.
An item has a key
and a corresponding value
that is expressed as a pair (key: value).
While the values can be of any data type and can repeat, keys must be of immutable type (string
, number
or tuple
with immutable elements) and must be unique.
As you can see from above, we can also create a dictionary using the built-in dict()
function.
Accessing Elements from Dictionary
While indexing is used with other data types to access values, a dictionary uses keys. Keys can be used either inside square brackets []
or with the get()
method.
If we use the square brackets []
, KeyError
is raised in case a key is not found in the dictionary. On the other hand, the get()
method returns None if the key is not found.
Output
Changing and Adding Dictionary elements
Dictionaries are mutable. We can add new items or change the value of existing items using an assignment operator.
If the key
is already present, then the existing value gets updated. In case the key
is not present, a new (key: value)
pair is added to the dictionary.
Output
Removing elements from Dictionary
We can remove a particular item in a dictionary by using the pop()
method. This method removes an item with the provided key and returns the value.
The popitem()
method can be used to remove and return an arbitrary (key, value)
item pair from the dictionary. All the items can be removed at once, using the clear()
method.
We can also use the del
keyword to remove individual items or the entire dictionary itself.
Output
Python Dictionary Methods
Methods that are available with a dictionary are tabulated below. Some of them have already been used in the above examples.
Method | Description |
---|---|
| Removes all items from the dictionary. |
| Returns a shallow copy of the dictionary. |
| Returns a new dictionary with keys from seq and value equal to |
| Returns the value of the key. If the key does not exist, returns |
| Return a new object of the dictionary's items in |
| Returns a new object of the dictionary's |
| Removes the item with the |
| Removes and returns an arbitrary |
| Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of |
| Updates the dictionary with the |
| Returns a new object of the dictionary's values |
Here are a few example use cases of these methods.
Output
Python Dictionary Comprehension
Dictionary comprehension is an elegant and concise way to create a new dictionary from an iterable in Python.
Dictionary comprehension consists of an expression pair (key: value)
followed by a for statement inside curly braces {}
.
Here is an example to make a dictionary with each item being a pair of a number and its square.
Output
This code is equivalent to
Output
A dictionary comprehension can optionally contain more for or if statements.
An optional if statement can filter out items to form the new dictionary.
Here are some examples to make a dictionary with only odd items.
Output
Other Dictionary Operations
Dictionary Membership Test
We can test if a key is in a dictionary or not using the keyword in
.
Notice that the membership test is only for the keys and not for the values.
Output
Iterating Through a Dictionary
We can iterate through each key in a dictionary using a for loop.
Output
Dictionary Built-in Functions
Built-in functions like all()
, any()
, len()
, cmp()
, sorted()
, etc. are commonly used with dictionaries to perform different tasks.
Function | Description |
---|---|
| Return True if all keys of the dictionary are True (or if the dictionary is empty). |
| Return True if any key of the dictionary is true. If the dictionary is empty, return False. |
| Return the length (the number of items) in the dictionary. |
| Compares items of two dictionaries. (Not available in Python 3) |
| Return a new sorted list of keys in the dictionary. |
Here are some examples that use built-in functions to work with a dictionary.
Output
Last updated