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 $$O(n)$$ 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
This gives you the exact same output as before.
Get A List Of Dictionary Keys
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
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()
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() if you want to capture the removed item, as
pop() returns the removed item:
Python dictionaries can be combined (merged) with the
As of Python 3.5 and higher, they can also be combined with the
** syntax below:
You can get a sorted list of the dictionary keys with the built-in
sorted() returns a new list, which contains all of dictionary keys in sorted order.
All popular implementations of Python implement dictionaries as hash tables. They use open addressing to resolve hash collisions.
|Operation||Average Case||Amortized Worst Case||Example|
|Table: Time complexities of the Python dictionary.|
defaultdicts have the same time complexities as a
This work is licensed under a Creative Commons Attribution 4.0 International License .
- Python Sets
- How To Parse Mathematical Expressions
- Parsing Command-Line Arguments In Python
- Bresenham's Line Algorithm