Python Dictionary Methods

Python has a set of built-in methods that you can use on dictionaries. 

This is what I will discuss in this article.

MethodDescription
clear()Removes all the elements from the dictionary
copy()Returns a copy of the dictionary
fromkeys()Returns a dictionary with the specified keys and value
get()Returns the value of the specified key
items()Returns a list containing a tuple for each key value pair
keys()Returns a list containing the dictionary's keys
pop()Removes the element with the specified key
popitem()Removes the last inserted key-value pair
setdefault()Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update()Updates the dictionary with the specified key-value pairs
values()Returns a list of all the values in the dictionary

 

Method get()

Example: get the value of the "age" item:

>>> person = {
	"name": "Mike",
	"age": 27,
	"position": "Developer"
}
>>> person.get("age")
27

If the dictionary doesn't have the key the method returns None:

>>> print(person.get("address"))
None

>>> person.get("address") is None
True

The method get() receives the second parameter which will be returned if the given key isn't found in the dictionary:

>>> person.get("address", "Brooklyn, NY 11216")
Brooklyn, NY 11216