A dictionary stores data as key-value pairs, something like mapping each key to a particular value. The built-in Python dictionary methods are a collection of distinct functions that operate only on dictionary objects. We can use these methods to work with dictionaries.
Once a dictionary is created, we can utilize the built-in dictionary methods in the Python programming language to access data, perform modifications, and perform data transformation. For example, merging two dictionaries, shallow copy, deleting all items from a dictionary, etc.
NOTE: For more information on Dictionaries, please refer to the Python dictionary article available on the Python Tutorial page.
List of Python Dictionary methods
There are about 11 built-in dictionary methods in the Python language to work on individual keys, values, and both.
Many built-in methods for dictionaries in the Python programming language allow performing deletions, accessing keys and their values, manipulation, updates, and more. The following table lists the available built-in dictionary functions.
| Functions | Description |
|---|---|
| copy | It returns a shallow copy of a dictionary. |
| clear | It removes all items from a dictionary. |
| fromkeys | Creates a dictionary from a given key sequence. |
| get | It returns a value for a given key. |
| items | It returns the total keys and their values in a dictionary. |
| keys | Returns a list of keys in a dictionary. |
| pop | It removes and returns the dictionary item of a given key. |
| popitem | It removes and returns the last item inserted into a dictionary. |
| setdefault | If it exists, it returns the value of a given dictionary key. Otherwise, it creates a new key with a value. |
| update | Update a dictionary key-value pair from another dictionary. |
| values | Returns a list of existing values in a dictionary. |
Python dictionary methods Examples
The above-mentioned list shows all the available dictionary methods. We start this series of examples with simple ones like clear(), copy(), keys(), and values(). These function provides a basic idea of Python dictionary methods, so that understanding the remaining becomes easy.
clear()
The clear() method is one of the built-in Python dictionary methods that removes all elements, including keys and values, from a dictionary. So, once you apply the clear() function, the dictionary becomes empty.
To demonstrate the clear() function, we have declared a student’s marks dictionary with five subjects. We will use the same dictionary for most of the upcoming examples.
sm = {"eng": 89, "math": 94, "phy": 79, "chem": 81,"bio": 80}
sm.clear()
print(sm)
Result
{}
copy()
The copy() dictionary method in Python shallow copies the existing dictionary into a new dict.
sm = {"eng": 89, "math": 94, "phy": 79, "chem": 81,"bio": 80}
new = sm.copy()
print(sm)
print(new)
Result
{'eng': 89, 'math': 94, 'phy': 79, 'chem': 81, 'bio': 80}
{'eng': 89, 'math': 94, 'phy': 79, 'chem': 81, 'bio': 80}
TIP: Any operations on the duplicate dictionary “new” will not reflect on orginal “sm” dictionary.
keys() – Python dictionary methods
The dictionary keys() method returns a complete list of keys in a dictionary. Next, we can use the list() function to convert this dict_keys() view object into a list for further access.
k = sm.keys()
print(k)
kl = list(sm.keys())
print(kl)
Result
dict_keys(['eng', 'math', 'phy', 'chem', 'bio'])
['eng', 'math', 'phy', 'chem', 'bio']
values()
The values() function is one of the Python dictionary methods that returns a view object of values in a dictionary. Next, we can use the list() function to convert this dict_values() view object into a list for further access/modifications.
v = sm.values()
print(v)
vl = list(sm.values())
print(vl)
Result
dict_values([89, 94, 79, 81, 80])
[89, 94, 79, 81, 80]
items() – Python dictionary methods
The items() function is one of the dictionary methods that returns a view object of key-value pairs in a dictionary. It returns a view object of the dict_items class with a list of tuples where each tuple is a key-value pair.
Next, we can use the list() function to convert this dict_items() view object into a list to access the key-value pair.
sm = {"eng": 89, "math": 94, "phy": 79, "chem": 81,"bio": 80}
ls = list(sm.items())
print(ls)
print(ls[1])
[('eng', 89), ('math', 94), ('phy', 79), ('chem', 81), ('bio', 80)]
('math', 94)
TIP: Otherwise, use the for loop to iterate over items and print them.
get()
The get() function is a built-in dictionary function in Python language to return the value of a particular (given) key. The get() method is the most powerful way to access the dictionary values based on keys.
sm = {"eng": 89, "math": 94, "phy": 79, "chem": 81,"bio": 80}
print(sm.get("phy"))
print(sm.get("bio"))
Result
79
80
NOTE: Use the second argument to provide a default value for the non-existing key-value pair.
pop() – Python dictionary methods
The pop() function is one of the dictionary methods that accepts a key as the input argument. Next, it removes the given key and the corresponding value. The pop() function returns the value of a given key as an output.
NOTE: If the given key is not present in a dictionary, it returns keyError. So, use the second argument for a default custom message, instead of keyError.
print(sm.pop("chem", None))
print(sm)
Result
81
{'eng': 89, 'math': 94, 'phy': 79, 'bio': 80}
popitem()
The popitem() is one of the Python dictionary methods that removes the last inserted key-value pair from a dictionary. The popitem() function returns the last inserted key-value as an output.
TIP: It follows the Last In First Out (LIFO) approach.
sm = {"eng": 89, "math": 94, "phy": 79, "chem": 81,"bio": 80}
print(sm.popitem())
print(sm)
print(sm.popitem())
print(sm)
Result
('bio', 80)
{'eng': 89, 'math': 94, 'phy': 79, 'chem': 81}
('chem', 81)
{'eng': 89, 'math': 94, 'phy': 79}
fromkeys() – Python dictionary methods
The fromkeys() function is one of the dictionary methods that creates a new dictionary using a sequence of keys.
In the following example, we have declared four keys. Next, used the fromkeys() function with a default value of 85. So, it creates a new dictionary with 4 keys, and each key has a value of 85.
ky = {"eng", "math", "phy", "chem"}
sm = dict.fromkeys(ky, 85)
print(sm)
{'eng': 85, 'phy': 85, 'math': 85, 'chem': 85}
setdefault()
If the key exists, the setdefault() function is one of the Python dictionary methods that returns the corresponding value of a given key. If the key is not present, that key will be inserted with the given default value.
The first statement, setdefault(‘math’)) Returns the value of the math key because it exists. The sm.setdefault(‘bio’, 88) inserts a new key-value pair because the sm dictionary has no existing bio key. To check it, we used the print() statement to display the dictionary with a new value.
sm = {"eng": 90, "math":87, "phy":76, "chem":90}
print(sm.setdefault('math'))
print(sm.setdefault('bio', 88))
print(sm)
87
88
{'eng': 90, 'math': 87, 'phy': 76, 'chem': 90, 'bio': 88}
update()
The update() function is one of the Python dictionary methods that uses another dictionary to update the key-value pairs in the current dictionary. We can call the update() function the dictionary merger.
In the following statement, we have declared two dictionaries. Next, we use the update() function to update the sm dictionary by adding the key-value pairs from the st dictionary.
sm = {"eng": 89, "math": 94}
st = {"bio": 74, "chem": 81}
sm.update(st)
print(sm)
{'eng': 89, 'math': 94, 'bio': 74, 'chem': 81}
Common Python dictionary methods
Apart from the above-mentioned dictionary-specific built-in Python dictionary methods, there are some common methods that we can use on dictionaries. Theya re:
| Functions | Description |
|---|---|
| len | It returns the length of a dictionary. |
| min() | It returns the minimum value in a dictionary. |
| max() | Returns the maximum value in a dictionary. |
| sorted() | Sorts the dictionary by keys, values, and both. |
| sum() | It returns the sum of all dictionary values. |
| all() | It returns TRUE if all dictionary items return True. |
| any() | It returns TRUE if at least one dictionary item is True. |
Dictionary len()
The built-in dictionary len() function returns the total number of items (length) in a dictionary. It helps to find out the total number of key-value pairs, and we can utilize this information for further manipulation.
Syntax
The syntax of the dictionary len() function is
len(dictionay_name)
The following example uses the same dictionary that we specified in the previous series of examples.
sm = {"eng": 89, "math": 94, "phy": 79, "chem": 81,"bio": 80}
print(len(sm))
Result
5
Python Dictionary method min()
The dictionary min() method finds the minimum key-value in a given dictionary.
Syntax
The syntax of the dict min() function to get the minimum value is
min(dictionary_name)
The min() function accepts a dictionary as an argument and finds the minimum value in it. By default, it finds the minimum key.
In the following program, we used keys() and values() to find the minimum key and value in a dictionary.
print(min(sm))
print(min(sm.keys()))
print(min(sm.values()))
Result
bio
bio
79
Dictionary max()
The max() function is one of the built-in common methods that can be used on Python dictionary items to find the maximum key or value in a given dictionary.
Syntax
The syntax of the dict max() function to get the maximum value is
max(dictionary_name)
The max() function accepts a dictionary argument and finds the maximum value in it. By default, it finds the maximum key.
In the following program, we used keys() and values() to find the maximum key and value in a dictionary.
print(max(sm))
print(max(sm.keys()))
print(max(sm.values()))
Result
phy
phy
94
Dictionary sorted()
The sorted() function is another common built-in method that we can use on dictionary items to sort the keys or values in ascending or descending order.
By default, it sorts the dictionary by keys. So, we must use the values() function to sort them by values. Next, use the reverse argument to set its value to True to sort items in descending order.
The first statement sorts the dictionary items by key (it is the default behaviour). In the second statement, we used reverse = True, instructing the sorted() function to perform descending order.
print(sorted(sm))
print(sorted(sm, reverse = True))
print(sorted(sm.keys()))
print(sorted(sm.values()))
print(sorted(sm.values(), reverse=True))
Result
['bio', 'chem', 'eng', 'math', 'phy']
['phy', 'math', 'eng', 'chem', 'bio']
['bio', 'chem', 'eng', 'math', 'phy']
[79, 80, 81, 89, 94]
[94, 89, 81, 80, 79]
sum() dictionary method in Python
There is one more common built-in function, sum(), that we can use on Python dictionaries to find the total or sum of the total numeric dictionary values or keys.
NOTE: You must specify the keys or values explicitly to avoid errors because it only works with numerical values.
print(sum(sm.values()))
Result
423
Dictionary all()
The all() function is one of the common built-in methods that can be used on Python dictionaries to find out whether all dictionary key has the values and vice versa. If every key has a corresponding value, it returns True. Otherwise, it returns False.
In the following example, there are three keys in a dictionary, where the last key, “bio,” has no value. If you use the all() function with values(), it will return False because there is a missing value for one key.
sm = {"eng": 89, "math": 94, "bio": None}
print(all(sm.values()))
False
TIP: If you check with keys, all(sm.keys()), the above example returns True because all items have keys.
In this example, the last has a value, but there is no corresponding key. So, the all function in the first statement returns False. On the other hand, the second one returns true because there are three items and each has a value.
sm = {"eng": 89, "math": 94, None: 81}
print(all(sm.keys()))
print(all(sm.values()))
Result
False
True
Python Dictionary method any()
The any() function is a common built-in dictionary method that returns if True if any one of the conditions is True. If there is at least one key or value, the any() function returns True. Otherwise, it returns False.
In the following example, the last item has no key or value. key, “bio,” has no value. However, the any() function returns True because it needs at least one key or value, and tehre are two key-value pairs.
sm = {"eng": 89, "math": 94, None: None}
print(any(sm))
print(any(sm.keys()))
print(any(sm.values()))
Result
True
True
True
Best Practices of Python dictionary methods
Please follow the best practices mentioned below to avoid common errors while working with dictionary methods.
Use get() to access Dictionary data
Instead of square brackets, we must always use the get() function to access the dictionary values. If the key does not exist, the square brackets raise KeyError. On the other hand, the get() function returns None, so we can even provide a default value.
The following example returns KeyError because there is no ‘bio’ key in ‘sm’.
sm = {"eng": 89, "math": 94}
print(sm['bio']) # KeyError
If we use get(), it returns None.
print(sm.get('bio')) # returns None
get() with default value.
print(sm.get('bio', 100)) # returns 100
Using pop() without a default value
If we use pop() without a default value, the pop() function returns a KeyError if it does not find the given key. For example,
sm = {"eng": 89, "math": 94}
print(sm.pop("sql"))
The above code returns a KeyError because there is no sql key in the sm dictionary. To avoid the same, use the default value.
print(sm.pop("sql", None))
The above returns None instead of KeyError.