Reference to Python Dictionary Methods
In Python, dictionaries come with a set of dedicated methods designed specifically for handling key–value pairs efficiently. These methods, often referred to as dictionary functions, work only with the dictionary data type. This tutorial presents all dictionary methods in alphabetical order, serving as an ultimate and up-to-date reference for developers.
Alphabetical Reference
The following table contains all 11 dictionary related methods in Python in alphabetical order.
Method | Description |
---|---|
clear() | This Python method clears all the elements from a dictionary. |
copy() | To create a shallow copy of a dictionary, we use this Python method. |
fromkeys() | To create a new dictionary with specified keys and values, we use this Python method. |
get() | This Python method returns the value of the given key from a dictionary. |
items() | This Python method returns a list of dictionary items as key and value pairs. |
keys() | To get a list of keys of a dictionary, we utilize this Python method. |
pop() | This Python method removes an element at a given key index in a dictionary and returns it. |
popitem() | To remove the last inserted key-value pair from a dictionary, we use this Python method. |
setdefault() | This Python method sets the default value of a key and returns it in a dictionary. |
update() | To update the dictionary with a specified key-value pair, we can use this Python method. |
values() | This Python method returns a list of all the values of a dictionary. |
Dynamically Get Python Dictionary Methods
Python offers a range of methods for working with dictionaries, and you can retrieve the complete, up-to-date list dynamically using the script below.
Get Python Dictionary Methods
# Get the list of dictionary methods dictionary_methods = [ method for method in dir(dict) if callable(getattr(dict, method)) and not method.startswith('__') ] # Print the list of dictionary methods print(dictionary_methods)
Python Dictionary-Related Functions
While Python offers dedicated dictionary methods, there are also several built-in functions and older utilities that interact with dictionaries in various ways.
The table below lists these 9 functions, excluding the common 11 dictionary methods, and serves as a handy reference for developers.
Function | Description |
---|---|
dict() | Creates a new Python dictionary. |
haskey() | Checks if a specified key exists in a dictionary. |
iter() | Returns an iterator over the dictionary keys. |
iteritems() | Returns an iterator over key-value pairs of the dictionary. |
iterkeys() | Returns an iterator over the keys of the dictionary. |
itervalues() | Returns an iterator over the values of the dictionary. |
viewitems() | Returns a view object of the dictionary’s key-value pairs. |
viewkeys() | Returns a view object of the dictionary’s keys. |
viewvalues() | Returns a view object of the dictionary’s values. |