Python Dictionary Methods with Example

Python Dictionary Methods

Now, we are going to have a look at some very interesting, useful, and important methods, which help us do different things, like clearing the dictionary, getting all the keys from the dictionary, getting all the values from the dictionary, etc. Let’s have a look at those different methods, one by one, and we are also going to consider taking some examples so that it becomes easy for us to understand. Let’s first list all the methods that we are going to consider here –

Python Dictionary Methods

MethodDescription
clear()As the name of the method says, the clear method clears the dictionary, which means that all the items are removed from the dictionary.
copy()This method returns a copy of the given dictionary. We are going to have a look at an example, which would make things much clear.
fromkeys()This method creates a new dictionary, from the given iterable, and the values are set to the given value. We are going to see an example of this method ahead.
get()This method returns the value corresponding to the key if the key is present. We are going to have an example of this method ahead.
items()This method returns a view object, which contains the key-value pairs of the dictionary.
keys()This method returns a view object, which contains the keys of the dictionary.
pop()As the name of the method says, it is going to remove the element with the specified key from the dictionary.
popitem()This method removes the last inserted key-value pair.
setdefault()This method returns the value of the specified key.  If the key does not exist, the key is inserted with the given default value. If the default value is not given, it defaults to None.
update()This method updates the dictionary with the specified items in the dictionary. Those specified items can be a dictionary, or an iterable, with key-value pairs.
values()This method returns a view object, which contains the values of the dictionary.