In this tutorial, we will learn what are Python Dictionary Methods and how to use them in Python programs to create, access, update and delete dictionaries:
Python Dictionary is a collection of key-value pairs that are widely used in programs and are also a fundamental part of the Python implementation.
For example, the Python built-in functions live in __builtins__.__dict__.
Because of their importance, it is crucial to know its built-in methods so that manipulating (creating, accessing, deleting, etc) them will be a child’s play.
=> Explore The Simple Python Training Series Here
Table of Contents:
Python Dictionary Methods
Just like any other Python data type, Dictionaries have built-in methods that can be used to manipulate their elements. Given below is a summary of these methods. You can get more details from the Python Official Documentation page.
Python Built-in Dictionary Methods
Name | Syntax | Description |
---|---|---|
items | d.items() | Returns each key-value pair of a dictionary, d, as a tuple. |
get | d.get(k[, default]) | Returns the value associated with the key(k). If k doesn’t exist, returns default if defined, otherwise returns None. |
keys | d.keys() | Returns all the keys defined in the dictionary, d |
values | d.values() | Returns all the values in the dictionary, d |
pop | d.pop(k[, default]) | Removes the key(k) from the dictionary and returns its value, else return default if k not in the dictionary, d. |
popitem | d.popitem() | Returns and removes a key-value pair from the dictionary, d, in a LIFO order. |
clear | d.clear() | Remove all elements from the dictionary, d |
update | d.update(b) | Add all objects from dictionary b to dictionary d. |
copy | d.copy() | Returns a shallow copy of the dictionary, d |
setdefault | d.setdefault(k[,default]) | Returns the value associated with the key, k, if exist, else returns default and sets key, k, to default in the dictionary, d |
fromkeys | d.fromkeys(s[, value]) | Create a new dictionary with keys from the sequence, s, and values set to value. |
Create A Dictionary
To recap, a dictionary is formed by having a bunch of key-value pairs enclosed by a curly bracket. We can create dictionaries in two ways:
Creating Dictionaries With {} And Dict()
With the curly bracket({}) and built-in dict() class, we can create empty dictionaries and dictionaries with user-defined data(key-value pairs).
Example 1: Create empty dictionaries and print their contents.
This is useful when we don’t know the elements that our dictionary will hold beforehand.
my_dict_one = {} # create empty dict with curly brackets my_dict_two= dict() # create empty dict with built-in dict() print(my_dict_one) print(my_dict_two)
Output
Example 2: Create dictionaries with data and print their contents.
Still, by using the curly brackets({}) and built-in dict(), we can create our dictionary and pass in elements that the dictionary will hold. This is useful when we know beforehand what data our dictionary will hold.
The code below shows the various ways of building a dictionary with {} and dict()
my_dict_one = {'one':1,'two':2,'three':3} # with curly brackets print("My Dict One: ",my_dict_one) my_dict_two = dict({'one':1,'two':2,'three':3}) # with curly brackets in dict() print("My Dict Two: ",my_dict_two) my_dict_three = dict(one=1,two=2,three=3) # with dict() and keyword-arguments print("My Dict Three: ",my_dict_three) my_dict_four = dict(zip(['one','two','three'],[1,2,3])) # with dict() and lists in zip() print("My Dict Four: ",my_dict_four) my_dict_five = dict([('one',1),('two',2),('three',3)]) # with dict() and list of tuples print("My Dict Five: ",my_dict_five)
Output
Creating Dictionary With Dictionary Comprehensions
This is a powerful way to build a dictionary by operating on iterable. Dictionary comprehensions were introduced to replace for-loops. However, not all for-loops can be written as a dictionary comprehension.
Example 3: Create a new dictionary where the key is the double of a number in the range from 0 to 5 and the value is the square of the number
Solution 3.1: Using the for-loop
def dict_from_range(): new_dict = {} # create our empty dict to hold the result r = range(0,5) # range from 0 to 5 #iterate through the range for value in r: new_value = value**2 # assign value as the square of the number key = value*2 # assign key as the double of the number new_dict[key] = new_value # add to dict. return new_dict if __name__ == '__main__': new_dict = dict_from_range() print("NEW DICT: ", new_dict)
Output
Solution 3.2: Using dict comprehensions
new_dict = {val*2: val**2 for val in range(0,5)} print(new_dict)
Output
From the solutions above, we see that using a dict comprehension is elegant and concise.
Creating Dictionaries With Dictionary Methods
The Python dictionary has certain methods that we can use to create new dictionaries from existing dictionaries.
#1) dict.fromkeys(s[,value])
This dictionary method creates a new dictionary with keys from the sequence, s, and values set to value. If the value is not defined, all the keys will be mapped to None.
This is useful when we have a bunch of keys and we want to give them the same initial value.
Example 4: Create a dict with the list of keys [‘one’,’One’,’ONE’] and give them each the value of 1.
my_dict_six = dict.fromkeys(['one','One','ONE'],1) # all keys mapped to the value '1' print(my_dict_six)
Output
The code below shows the result without the value defined.
my_dict_seven = dict.fromkeys(['four','five','six']) # value is not defined, all keys mapped to None. print(my_dict_seven)
Output
#2) d.copy()
This method returns a shallow copy of the dictionary.
NB: Shallow means it copies just one level deeper.
Example 5: Create a copy of a nested dictionary and demonstrate that a shallow copy was made.
nested_dict = {'a':0,'b':1,'c':{'d':3,'e':4}} # our nested dict print("Nested Dict: ", nested_dict) nested_dict_cpy = nested_dict.copy() # make a copy of the dict print("nested Dict Copy: ", nested_dict_cpy) nested_dict['a'] = -1 # change value of key 'a' in original dict print("Changed Dict: ", nested_dict) print("Nested Dict Copy: ", nested_dict_cpy) # copied dict remains unchanged nested_dict['c']['d'] = -3 # change value of key 'd' two level deep print("Two level changed Dict: ", nested_dict) print("Nested Dict Copy: ", nested_dict_cpy) # copied dict changes as well
Output
Insert Keys And Values In A Dictionary
After we have created our dictionary, we may want or have to add some elements (key-value pairs) into our dictionary.
The most common way to add key-value pairs into a dictionary is by indexing
d[keys] = value
Example 6: Add the key-value pairs “Monday”:1, and “Tuesday”: 2 into an empty dict.
my_dict = {} # create an empty dict print("My Empty Dict: ",my_dict) my_dict['Monday'] = 1 # add key 'Monday' and value 1 print("First Item Inserted: ", my_dict) my_dict['Tuesday'] = 2 # add key 'Tuesday' and value 2 print("Second Item Inserted: ", my_dict)
Output
Also, the Python dictionary provides several methods that we can use to add in elements.
#1) d.setdefault(k[,default])
This dictionary method returns the value associated with the key, k, if exists, else returns default and sets key, k, to default in the dictionary, d.
From the explanation above, we notice that this method actually does two things.
- Set the key, k to the default value if k doesn’t exist in the dictionary.
- It returns the value associated with the key k.
However, in this section, we shall focus on its first functionality.
This method is useful in many cases. One of them is that it can be used to add elements to the value of an existing key or set it to default.
Example 7: Add names of cars one at a time, to the list of an empty dictionary with key Cars.
my_cars = {} # create an empty dict print("My empty Dict: ",my_cars) my_cars.setdefault('Cars',[]).append("BMW") #add a car print("First Item Added: ", my_cars) my_cars.setdefault('Cars',[]).append("Toyota") # add a second car print("Second Item Added: ", my_cars) my_cars.setdefault('Cars',[]).append("Honda") # add a third car print("Third Item Added: ",my_cars)
Output
To feel the advantage of using the method setdefault() in this example, let’s do the same using the if not in the statement.
def add_items(): # Add using for in statement my_dict = {} # create an empty dict # verify if key in dict if 'Cars' not in my_dict: # if not in dict, add key and initialize to an empty list. my_dict['Cars'] = [] # add new value to the key's list value. my_dict['Cars'].append('Toyota') print("Cars: ",my_dict) if __name__ =='__main__': add_items()
Output
From the sample code above, we see that without our setdefault() method, we first have to check if the key exists in our dict and set it to an empty list if it doesn’t exist. These are exactly what our setdefault() method do for us under the hood.
#2) d.update(b)
The dictionary method update() will update all objects from dictionary b to dictionary d.
As we shall see later in this tutorial, the update() method also updates key values in a dictionary. However, for now, we will focus on the “adding” functionality of this method.
Example 8: Add all objects of one dictionary to the other.
dict_1 = {'one':1,'two':2,'three':3} # first dict print("Dict 1: ", dict_1) dict_2 = dict([('four',4),('five',5)]) # second dict print("Dict 2: ", dict_2) dict_1.update(dict_2) # add all objects of first dict to second dict print("Updated Dict 1: ", dict_1)
Output
Someone without the knowledge of this method will loop through the dictionary by extracting its key-value pairs and using indexing to add each pair to the other dictionary.
def update_with_loop(): dict_1 = {'one':1,'two':2,'three':3} # first dict dict_2 = dict([('four',4),('five',5)]) # second dict print("DICT_1 before: ", dict_1) # loop through dict_2 for k,v in dict_2.items(): # add the key-value pair to dict_1 dict_1[k] = v print("DICT_1 after: ", dict_1) if __name__ =='__main__': update_with_loop()
Output
Accessing A Dictionary
Just like how we can add many elements into a dict, we can also access these elements. The most common way to access key values from a dictionary is via indexing.
Example 9: Let’s access key values from the dictionary dict_1 that was created and updated above.
dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} print("Access Key 'one': ", dict_1['one']) # access value at key 'one' print("Access Key 'five': ", dict_1['five']) # access value at key 'five' print("Access Key 'three': ", dict_1['three']) # access value at key 'three'
Output
A Python dictionary has two main components that we can access and manipulate: key and value, and the dictionary provide several methods that we can use to access these components.
Accessing Values
As we saw above, the main and common way to access dictionary values is via indexing. However, this approach is dangerous because if we try to access the value of a key that doesn’t exist, then Python will raise a KeyError exception.
dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} print("Access Key: ", dict_1['six']) # access value at key 'six', which doesn't exist
Output
In this section, we shall see the various dictionary methods that can help us safely access the dictionary’s values.
#1) d.get(k[, default])
The Python dictionary get() method returns the value associated with the key(k) if k exists, else it returns default if defined, otherwise returns None.
This is by far the safest way to get values associated with keys in a dictionary. At times, we are not sure if a key is defined in a dictionary, hence to prevent Python from raising an exception, we either define a default value that will be returned if the key doesn’t exist or still, we can rely on the default None value that this method will return.
Example 10: Use the dictionary method get() to retrieve values from the dictionary dict_1 defined above. Define default returned values for some, and rely on the default None for others.
dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} # our dictionary print("Access key 'one': ",dict_1.get('one', 0)) # access value at key 'one', define default of 0 print("Access key 'six': ",dict_1.get('six', 6)) # access value at key 'six', define default of 6 print("Access key 'six' with no default: ", dict_1.get('six')) # access value at key 'six', rely on default of None
Output
From the code example above, the index ‘six’ doesn’t exist in the dictionary. So, our defined default value, 6 is returned. Also, a None is returned in the last line of code as we haven’t defined a default value.
#2) d.values()
This dictionary method returns all values in the dictionary as a dictionary view object.
dict_values([value1, value2,....,valueN])
This object can be converted into a set, tuple, list, or directly iterated through, based on the need.
Example 11: Return all values of the dictionary dict_1 as a tuple
dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} # our dictionary dict_as_tuple = tuple(dict_1.values()) # wrap in tuple() to convert to tuple print(dict_as_tuple)
Output
Accessing Keys
The Python dictionary just has one method that is solely used to return keys from a dictionary.
#1) d.keys()
This method returns all the keys in the dictionary as a dictionary view object.
dict_keys([key1, key2,....,keyN])
Just like d.value(), this returned object can be converted into a set, tuple, list, or directly iterated through, based on need.
Example 12: Return all keys from the dictionary dict_1 as a view object and convert the object into a list.
dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} # our dictionary k_obj = dict_1.keys() # get all keys as view object print("All Keys: ", k_obj) print("List of Keys: ", list(k_obj)) # convert into a list
Output
Accessing Key-Value Pairs
At times it is necessary to access dictionary key-value pairs. Imagine if we want to compute the dictionary values, and create a new dictionary with the new values but maintaining the keys.
The Python dictionary has a method that is solely used for this purpose.
#1) d.item()
This method returns each key-value pair of a dictionary as a dictionary view object of tuples.
dict_items([(value1,key1),(value1,key1),...,(valueN,keyN)])
The view object can be converted into a list, tuple, set, or iterated through based on need. In the example below, we shall iterate through the resulting view object with a for-loop.
Example 13: Double each value of the dictionary and create a new dictionary with the new values but with the same keys.
def double_value_new_dict(d): new_dict = {} # create a new dict # iterate through the view object of key-value pairs for key, value in d.items(): new_value = value * 2 # double the value new_dict[key] = new_value # insert the new value and key into the new dict. return new_dict if __name__ == '__main__': dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} new_dict = double_value_new_dict(dict_1) print("OLD DICT: ", dict_1) # print the original dict print("NEW DICT: ", new_dict) # print the new dict
Output
Check For Membership
In this section, we shall see how to check for the occurrence of values and keys in a dictionary. The most common operator used to check for an element in a dictionary is the in operator.
This operator also works in a list but gets slower as the list increases. This is not the case for dictionaries as dictionaries use a hash function that makes it effective as the time taken to look for elements is independent of the size of the dictionary.
Check For Keys
This is necessary if we want to be sure that a specific key exists before accessing its value.
Example 14: Check if the keys ‘one’ and ‘six’ exist in the dictionary dict_1
dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} #our dictionary print('one' in dict_1) # check for key 'one' print('six' in dict_1) # check for key 'six'
Output
Check For Values
This is necessary if we want to make sure that a specific value exists in our dictionary.
NB: The expression element in d as seen above checks for keys and not value. To check for values, we should explicitly use d.values()
Example 15: Check for values 3 and 7 in the dictionary dict_1
dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} # our dict print(3 in dict_1.values()) # check for value 3 print(7 in dict_1.values()) # check for value 7
Output
Delete From A Dictionary
Most dictionary methods that delete elements from a dictionary also return these elements. However, the del keyword can be used to delete an element by key without a return.
#1) d.pop(k[, default])
The dictionary pop() method Removes the key(k) from the dictionary and returns its value, else returns default if k not in the dictionary.
NB: If the key is not in the dictionary and default not defined, a KeyError exception will be raised.
Example 16: Remove and return values of keys ‘one’ and ‘seven’ from the dictionary dict_1 . Return 0
dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} dict_new = dict_1.copy() # make a copy to work with print("Dict: ", dict_new) pop_one = dict_new.pop('one',0) # remove and return for key 'one' print(pop_one) pop_seven = dict_new.pop('seven',0) # remove and return for key 'seven' print(pop_seven) print("Dict after pop: ", dict_new)
Output
NB: We used the dictionary copy() method to make a shallow copy of our dictionary.
#2) d.popitem()
This method returns and removes a key-value pair from the dictionary in a LIFO(Last In First Out) order.
NB: This method doesn’t take any argument.
Example 17: Drop the last element of the dictionary dict_1
dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} dict_new = dict_1.copy() # make a copy to work with print("Dict before pop: ", dict_1) pop_item = dict_new.popitem() # delete and return the last elements print("Popped Item: ", pop_item) print("Dict after pop: ", dict_new)
Output
#3) d.clear()
This method removes all the elements from a dictionary. Unlike the del keyword(detailed below), it clears all elements rendering the dictionary empty rather than deleting the dictionary object.
NB: Unlike pop() and popitem(), the method clear() removes elements but doesn’t return them.
Example 18: Delete all the elements from the dictionary dict_1
dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} dict_new = dict_1.copy() # make a copy to work with print("Dict before clear: ", dict_new) dict_new.clear() # delete all elements from the dictionary print("Dict after cleared: ", dict_new)
Output
#4) del keyword
Though this is not a dictionary method, it is useful when we want to delete an element from a dictionary but we don’t want to return the deleted element.
Example 19: Delete the key ‘one’ from the dictionary without returning its value.
dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} dict_new = dict_1.copy() # make a copy to work with print("Dict before delete: ", dict_new) del dict_new['one'] # delete at key 'one' print("Dict after delete: ", dict_new)
Output
NB: This keyword can also be used to completely delete the dictionary object.
dict_new = {'two': 2, 'three': 3, 'four': 4, 'five': 5} # display our dict from the previous example print("Dict before delete: ", dict_new) del dict_new # delete the dictionary object print("Check object after delete: ", dict_new) # try to access it again. NameError raised
Output
Update A Dictionary
We can change the value of a key in a dictionary. The most common way is via indexing as shown below.
Example 20: In the dictionary dict_1, change the value of the keys ‘one’ and ‘two’ to 01 and 02 respectively.
dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} dict_new = dict_1.copy() # make a copy to work with print("Dict before update: ", dict_new) dict_new['one'] = '01' # change value of key 'one' dict_new['two'] = '02' # change value of key 'two' print("Dict after update: ", dict_new)
Output
Python dictionary has a method that can be used to update a dictionary.
#1) d.update(b)
This method adds all objects from dictionary b into dictionary d.
Earlier in this tutorial, we used the update() method to insert elements into a dictionary. However, in this section, we will see how to update the value of an existing key in a dictionary.
Example 21: Redo example 20 using the update() method.
dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} dict_new = dict_1.copy() # make a copy to work with print("Dict before update: ", dict_new) dict_new.update(one='01', two='02') #update the values at key 'one' and 'two' print("Dict after update: ", dict_new)
Output
Frequently Asked Questions
Q #1) Which is better, list or dictionary in Python?
Answer: The choice of either a list or dictionary depends on what we want to achieve.
If we are searching millions of items and speed is a concern, then using a dictionary is preferred as it is significantly faster than using the list.
If the order is a concern, then a list is preferred as it is an ordered sequence while a dictionary is unordered. But there is a specialized dictionary implemented in the Collections module that keeps the order of its items called OrderedDict.
Q #2) Are Dictionaries ordered?
Answer: Dictionaries are unordered. Also, the order doesn’t matter in dictionaries as it uses keys to access its values.
The code below shows that dictionaries are unordered.
print({'a':1,'b':2} == {'a':1,'b':2}) # have the same order print({'a':1,'b':2} == {'b':2,'a':1}) # have different order
Output
Q #3) Why is searching in a dictionary faster than a list?
Answer: Searching in a dictionary is faster because a dictionary uses a hash function. This makes the time taken to look up the elements independent of the size of the dictionary.
Q #4) Are dictionaries mutable?
Answer: Yes, dictionaries are mutable. Like List, they represent their data as objects and their data can be changed without changing their identity. Unlike the other objects like strings, tuples, integers which are immutable, they can’t be changed.
Conclusion
In this tutorial, we looked at Python dictionary methods. We saw how to create, access, update and delete dictionaries.
We also looked at the various ways to check for membership of keys and values in a dictionary.
=> Visit Here To Learn Python From Scratch