Python Dictionaries
A Python dictionary is a data structure which stores items in key—value pairs. It is unordered, mutable and indexed.
Python dictionaries are typically implemented as a hash table data structure. This enables lookup. See the (#typical-implementations) section for more information on how a Python dictionary is implemented in the back-end.
Checking If A Key Exists In A Dictionary
The recommended way to check if a key exists in a Python dictionary is to use the in
keyword, as shown in the code example below:
Iterating Over A Dictionary
Simple iteration can be done with the in
operator on the dictionary itself, which provides you with the keys in the dictionary:
Another way which is very similar but can save you from writing the code to get the value for each code yourself is to use the .items()
function:
This gives you the exact same output as before.
Get A List Of Dictionary Keys
Calling keys()
on a Python dictionary returns a dict_keys
object. A dict_keys
object is similar to a List, but you cannot index or modify the object.
If you really want a list, you can pass this dict_keys
object into the list()
constructor.
Iterating And Deleting Keys At The Same Time
Strictly speaking, you can’t iterate over a dictionary and delete entries at the same time. However, you can quite easily create a copy of the dictionary keys, iterate of that, and delete entries from the dictionary, as shown in the following example:
This does not occur much overhead as you are just copying the keys, and not the values.
Another way you can do it is by creating a new dictionary using dictionary comprehension:
This however creates a copy, and might be too memory intensive for large dictionaries.
del vs. pop()
Both del
and pop()
can be used to remove items from a dictionary:
It is recommended to use del
if you just want to delete the item, as it will be slightly faster than pop()
. Use pop()
if you want to capture the removed item, as pop()
returns the removed item:
Combining Dictionaries
Python dictionaries can be combined (merged) with the update()
function.
As of Python 3.5 and higher, they can also be combined with the **
syntax below:
Sorting Dictionaries
You can get a sorted list of the dictionary keys with the built-in sorted()
function:
sorted()
returns a new list, which contains all of dictionary keys in sorted order.
Typical Implementations
All popular implementations of Python implement dictionaries as hash tables. They use open addressing to resolve hash collisions.
Performance
Operation | Average Case | Amortized Worst Case | Example |
---|---|---|---|
Get Item | d[k] | ||
Set Item | d[k] = v | ||
Delete Item | del d[k] | ||
Iteration | for k in d: | ||
Copy | d2 = d1.copy | ||
Table: Time complexities of the Python dictionary. |
defaultdicts
have the same time complexities as a dictionary
.