Table of Contents
In this tutorial we will learn about Python Dictionary data type. Dictionaries, sometimes referred to as associative arrays in other languages, are data structures that hold data or information in a key-value order. Dictionaries allow you to access whatever value you want, using the much easier to remember key.
What are Python dictionaries
- A dictionary is a collection of unordered data, which is stored in key-value pairs.
- What is meant by “unordered” is the way it is stored in memory.
- It is not accessible through an index, rather it is accessed through a key.
- Lists are known as ordered data collections because each item is assigned a specific location.
- Dictionaries work like a real-life dictionary, where the key is the word and the values are the definition.
- Dictionaries are useful for working with large data, mapped data, CSV files, APIs, sending or receiving data, and much more.
Python dictionary types
Dictionaries, unlike lists, are indexed using keys, which are usually strings. There are two kinds of dictionaries that you can use in Python:
- the default dict, which is unordered, and
- a special kind of dictionary called an OrderedDict.
The difference is that the keys in the default dictionary are stored in an unordered manner, whereas an OrderedDict
stores key-value pairs in the order of insertion.
Comparison between different Python Data Types
Below table shows a summary of the differences between each data types:
Data Type | Ordered | Iterable | Unique | Immutable | Mutable |
---|---|---|---|---|---|
List | Yes | Yes | No | No | Yes |
Dictionary | No | Yes | Keys only | Keys only | Values only |
Tuple | Yes | Yes | No | Yes | No |
Set | No | Yes | Yes | No | Yes |
Frozenset | No | Yes | Yes | Yes | No |
Create Python dictionary
You can create python dictionary in two ways. The first way is to simply assign an empty dictionary to a variable by using curly brackets, like so:
dictionary = {}
The second way is to use the dict()
function to return a new dictionary:
dictionary = dict()
In both cases, a dictionary object will be created.
Exanple-1: Create python dictionary using {}
In this example we will create a dictionary using {}
. For the sake of simplicity I have distributed the content of cars into different lines but you can put all the keys and their values in single line as well.
#!/usr/bin/env python3 # dictionary cars = { 'hyundai': "i10", 'maruti': "swift", 'honda': "city" } print(cars)
Output from this script:
~]# python3 dictionary-example-1.py
{'hyundai': 'i10', 'maruti': 'swift', 'honda': 'city'}
Example-2: Create python dictionary using dict()
In this example we will use dict()
to create a python dictionary.
#!/usr/bin/env python3 # dictionary cars = dict( hyundai: "i10", maruti: "swift", honda: "city" ) print(cars)
Output from this script:
~]# python3 dictionary-example-1.py
{'hyundai': 'i10', 'maruti': 'swift', 'honda': 'city'}
dict()
function, we assign values to keys using the =
operator. When using {}
, we separate the keys (which are strings) from the values by using :
.
How to check object type
Method-1: Using isinstance()
The isinstance()
function is used to check the type of an object. It takes two arguments, the first one being the object being inspected, and the second being the class that we want to type-check against; for example, int
, str
, dict
, list
, and so on.
For example, in this python script I have a dictionary object. But we will check the type of the object using isinstance()
:
#!/usr/bin/env python3 # dictionary mydict1 = {'ab':1, 'bc':2, 'cd':3} print(isinstance(mydict1, dict))
Let's execute this script
~]# python3 dictionary-example-1.py
True
So this confirms that mydict1
is a dictionary.
Method-2: Using type()
Alternatively we can also use type()
to get the type of the object, I will update my code:
#!/usr/bin/env python3 # dictionary mydict1 = {'ab':1, 'bc':2, 'cd':3} print(type(mydict1))
Output from this script:
~]# python3 dictionary-example-1.py
<class 'dict'>
So this also confirms that mydict1
is a dictionary.
Add or append key value to existing Python dictionary
Example-1: Basic method to add new key value pair to python dictionary
To add or append a new key:value
pair to existing dictionary we must use
dictionary[KEY]=vVALUE
where dictionary is your variable which contains the actual dictionary. Replace KEY and VALUE with your key:value
pair which you want to add to the dictionary
Let's execute this script:
~]# python3 dictionary-example-2.py
Before adding: {'hyundai': 'i10', 'maruti': 'swift', 'honda': 'city'}
After adding: {'hyundai': 'i10', 'maruti': 'swift', 'honda': 'city', 'ford': 'ecosport'}
So a new key:value
pair i.e. ford:ecosport
was added to our cars
dictionary.
Example-2: Append new key:value pair using dict.update()
The .update()
method on dictionaries, is used to insert new key-value pairs into a dictionary, or update the value of an existing one. In this script we will append ford:ecoport
using dict.update()
to our existing dictionary cars
Output from the script:
~]# python3 dictionary-example-2.py
Before adding: {'hyundai': 'i10', 'maruti': 'swift', 'honda': 'city'}
After adding: {'hyundai': 'i10', 'maruti': 'swift', 'honda': 'city', 'ford': 'ecosport'}
Modify data in Python dictionary
Example-1: Basic method to replace value of existing key in the dictionary
In this example we will replace the value of one of the existing key in the dictionary. We will replace the value of honda:city
to honda:jazz
where jazz
will be the new value for honda
Output from this script:
~]# python3 dictionary-example-3.py
Before modifying: {'hyundai': 'i10', 'maruti': 'swift', 'honda': 'city'}
After modifying: {'hyundai': 'i10', 'maruti': 'swift', 'honda': 'jazz'}
So the value of honda
is modified to 'jazz
'
Example-2: Modify key value using dict.update()
In the previous example we used .update()
function to add new key value to existing dictionary, we can also use .update()
to modify the value of any existing key in the dictionary. For example I will use dict.update()
to modify the value of 'honda
' to 'jazz
'
Output from this script:
~]# python3 dictionary-example-2.py Before modifying: {'hyundai': 'i10', 'maruti': 'swift', 'honda': 'city'} After modifying: {'hyundai': 'i10', 'maruti': 'swift', 'honda': 'jazz'}
How to read data from Python dictionary
In this section we will access the dictionary values using their keys:
Example-1: Using key reference
We can use the key to get the mapping value details. In this example we will read the value of all the keys present in cars
dictionary:
Output from this script:
~]# python3 dictionary-example-2.py
i10
swift
city
But if a key is not defined then you may get KeyError
. I updated my script to lookup for key "ford
" which doesn't exist and hence the script failed:
~]# python3 dictionary-example-2.py
Traceback (most recent call last):
File "dictionary-example-2.py", line 10, in
print(cars['ford'])
KeyError: 'ford'
In such case we should use get()
function which we will use in our next example:
Example-2: Using get() function
The get()
function returns None
if an item does not exist. You can also use the get()
function to specify what should be returned when no value exists.
#!/usr/bin/env python3 # dictionary cars = { 'hyundai': "i10", 'maruti': "swift", 'honda': "city" } print('This key is present: ', cars.get('hyundai')) ## prints 'None' when key is not defined print('This key is not defined: ', cars.get('test')) ## prints custom message when key is not defined print(cars.get('test', 'Key test is not defined'))
Output from this script:
~]# python3 dictionary-example-4.py
This key is present: i10
This key is not defined: None
Key test is not defined
How to iterate through Python dictionary
I already covered this part in my previous chapter where I used for loop to iterate over dictionary. But let's discuss this in more detail here:
Example-1: Use for loop to iterate over dictionary
The simplest way to iterate through dictionaries is to use a for loop. Use a for loop as follows, in order to get a dictionary's keys:
#!/usr/bin/env python3 # dictionary cars = { 'hyundai': "i10", 'maruti': "swift", 'honda': "city" } for item in cars: print(item)
Output from this script:
~]# python3 dictionary-example-5.py
hyundai
maruti
honda
Example-2: Iterate over keys or values using keys() function in Python dictionary
You can also explicitly iterate through only the keys or the values of a dictionary by calling the keys()
method, which returns a list of keys, or the values()
method, which returns a list of values in the dictionary.
Use the keys()
method as follows, in order to print the keys:
#!/usr/bin/env python3 # dictionary cars = { 'hyundai': "i10", 'maruti': "swift", 'honda': "city" } print('Using .keys() to get the list of keys in cars dictionary') for item in cars.keys(): print(item) print('Using .values() to get the list of values in cars dictionary') for item in cars.values(): print(item)
Output from this script:
Example-3: Get both keys and value at the same time from Python dictionary
In the previous example we got the keys and values using different methods in separate code, we can also iterate over a dictionary and get both keys and values at the same time:
#!/usr/bin/env python3 # dictionary cars = { 'hyundai': "i10", 'maruti': "swift", 'honda': "city" } for key, value in cars.items(): print('The key is: ', key, 'and mapping value is: ', value)
Here we are using two variables with dict.items
to iterate over both key and the value and then print them on the console.
Output from this script:
How to check if a key exist in Python dictionary
In previous example we saw that when a key is not present and if we try to access them using print then we get KeyError
. We can use get()
function which we used earlier or in
keyword.
You can use the in
keyword to check whether a particular key exists in a dictionary, without iterating through it. This works the same way as it does in lists, and you will get back a Boolean value of True if the key exists, and False if it doesn't:
In this script we use in
keyword to check if a particular key exist in the Python dictionary:
Output from this script:
~]# python3 dictionary-example-6.py
True
False
We can also use this in if condition to check existence of dictionary and perform some task accordingly:
if 'hyundai' in cars: print('Found') else: print('Not Found')
How to remove all the data from Python dictionary with dict.clear()
The clear method is used to remove all keys from a Python dictionary.
#!/usr/bin/env python3 # dictionary cars = { 'hyundai': "i10", 'maruti': "swift", 'honda': "city" } cars.clear() ## clear the data from cars dictionary print(cars) ## print the content of cars dictionary
Here cars.clear()
will remove all the keys and values from cars dictionary. Output from this script:
~]# python3 dictionary-example-8.py
{}
As you see our dictionary is empty.
How to remove single key value pair from Python dictionary
Example-1: Using del keyword
If you only want to remove one key-value pair, you can use the del
keyword, for example we will delete maruti
from our cars
dictionary using del
keyword:
#!/usr/bin/env python3 # dictionary cars = { 'hyundai': "i10", 'maruti': "swift", 'honda': "city" } del cars['maruti'] ## delete maruti and mapping value print(cars) ## print cars dictionary content
Output from this script:
~]# python3 dictionary-example-6.py
{'hyundai': 'i10', 'honda': 'city'}
As you see, maruti
key and it's value was removed from the cars dictionary.
Example-2: Using dict.pop()
.pop()
is more useful if your intention is to remove the key pair from the dictionary and store it in a different variable for further usage.
#!/usr/bin/env python3 # dictionary cars = { 'hyundai': "i10", 'maruti': "swift", 'honda': "city" } var = cars.pop('honda') # remove honda key from cars print(cars) # print cars dictionary print(var) ## this will return value of honda
Output from this script:
~]# python3 dictionary-example-6.py
{'hyundai': 'i10', 'maruti': 'swift'}
city
So using pop()
we removed honda
from our dictionary and stored the value in different variable var
, then we access the value of var
How to copy content from one Python dictionary to another
We can use dict.copy()
to create shallow copies of Python dictionaries. In this example we copy the content of cars dictionary into cars_copy
and later update the content of cars dictionary to make sure the same is not updated in cars_copy
. So both the copies are not linked to each other in any way.
#!/usr/bin/env python3 # dictionary cars = { 'hyundai': "i10", 'maruti': "swift", 'honda': "city" } cars_copy = cars.copy() ## copying cars content cars.update({'honda':'jazz'}) ## update cars content print('original:', cars) ## print cars content print('duplicate: ', cars_copy) ## print cars_copy content
Output from the script:
~]# python3 dictionary-example-6.py
original: {'hyundai': 'i10', 'maruti': 'swift', 'honda': 'jazz'}
duplicate: {'hyundai': 'i10', 'maruti': 'swift', 'honda': 'city'}
So our original dictionary was updated but the same is not reflected in the duplicate copied dictionary.
Using dict.popitem() in dictionary
The popitem()
method pops and returns a random item from the Python dictionary. That item will no longer exist in the dictionary after that.
#!/usr/bin/env python3 # dictionary cars = { 'hyundai': "i10", 'maruti': "swift", 'honda': "city" } print(cars.popitem()) # remove any random key value print(cars) # print available content of cars
In this example I am using cars.popitem()
which will randomly remove one key value pair from the cars dictionary. Next we will print the available data from our dictionary:
~]# python3 dictionary-example-6.py
('honda', 'city')
{'hyundai': 'i10', 'maruti': 'swift'}
Using dict.setdefault() in Python dictionary
The setdefault()
method takes two arguments: a key to be searched for in the dictionary, and a value.
- If the key exists in the Python dictionary, its value will be returned.
- If the key does not exist, it will be inserted with the value provided in the second argument.
- If no second argument was passed, any insertion will be done with the value None.
Example-1: If key exists in the dictionary
Assuming the key exists in the Python dictionary which is used with setdefault()
#!/usr/bin/env python3 # dictionary cars = { 'hyundai': "i10", 'maruti': "swift", 'honda': "city" } var = cars.setdefault("maruti") print('cars dict: ', cars) print('new variable ', var)
Output from this script:
~]# python3 dictionary-example-12.py
cars dict: {'hyundai': 'i10', 'maruti': 'swift', 'honda': 'city'}
new variable swift
In this case, the value is returned as-is, and the dictionary is left untouched. Passing the second argument in this case will have no effect, since a value already exists.
Example-2: When key doesn’t exist in the dictionary and value was provided with key
Let's look at another example, where the key does not exist in the dictionary, and a value was passed. In this case, the key-value pair will be added to the dictionary, and the value will be returned, as well:
#!/usr/bin/env python3 # dictionary cars = { 'hyundai': "i10", 'maruti': "swift", 'honda': "city" } var = cars.setdefault("ford", "ecosport") print('cars dict: ', cars) print('new variable ', var)
Output from this script:
~]# python3 dictionary-example-13.py
cars dict: {'hyundai': 'i10', 'maruti': 'swift', 'honda': 'city', 'ford': 'ecosport'}
new variable ecosport
So I was trying to add value of ford
key using setdefault
but since it was not present, both key and value were added to the dictionary and then the new variable is able to return the value of new key
Example-3: When key doesn’t exist in the dictionary and value was “not” provided with key
Now, let's look at a final example, where the key does not exist in the dictionary, and no value was passed. In this case, the key will be added with a value of None. Nothing will be returned:
#!/usr/bin/env python3 # dictionary cars = { 'hyundai': "i10", 'maruti': "swift", 'honda': "city" } var = cars.setdefault("ford") print('cars dict: ', cars) print('new variable ', var)
Output from this script:
~]# python3 dictionary-example-6.py
cars dict: {'hyundai': 'i10', 'maruti': 'swift', 'honda': 'city', 'ford': None}
new variable None
Since this time we did not provided value for ford
key, the value is set as "None
"
Ordered Dictionary in Python
So far, the dictionaries that we have created do not maintain the insertion order of the key-value pairs that are added. Ordered dictionaries are dictionaries that maintain the insertion order of keys. This means that when you are iterating through them, you will always access the keys in the order in which they were inserted.
The OrderedDict
class is a dict
subclass defined in the collections package that Python ships with. Creating an ordered dictionary is as easy as creating an instance of the OrderedDict
class and passing in key-value pairs:
#!/usr/bin/env python3 from collections import OrderedDict cars = OrderedDict(hyundai='i10', maruti='swift') print(cars)
Output from this script:
~]# python3 dictionary-example-13.py
OrderedDict([('hyundai', 'i10'), ('maruti', 'swift')])
Everything about OrderedDict, except for it maintaining an internal key order, is similar to normal dictionaries
Conclusion
In this tutorial, we covered dictionaries and their types (the default, unordered dict
, and the specialized OrderedDict
). We also looked at attributes defined on dictionary objects and their use cases; for example, update
and setdefault
. Using these attributes, we learned how to iterate through dictionaries and modify them to achieve particular goals.
Further Readings
Python Dictionaries
Looping Techniques
Python Ordered Dictionary
Mistakes —here you don’t put the keys in quotes…the below example doesn’t work.
Example-2: Create dictionary using dict()
In this example we will use dict() to create a python dictionary.
2)
isinstance
example doesn’t seem to work with python 3 and above.Thanks for highlighting this. I have corrected (1) but for (2) I see
isinstance()
is supported with Python3.Xhttps://docs.python.org/3/library/functions.html#isinstance
It also works in my environment with