Home »
Python
Python Dictionaries: A Complete Tutorial With Examples
Python Dictionaries: In this tutorial, we will learn about the Python dictionaries with the help of examples.
By Abhishek Jain Last updated : June 09, 2023
What is a dictionary in Python?
A dictionary is a mapping between a set of indices (keys) and a set of values. It is an extremely useful data storage construct where each element is accessed by a unique key.
A dictionary is like a list, just different in indexing. In a list, an index value is an integer, while in a dictionary index value can be any other data type called keys. It stores and retrieves the key-value pairs, where each value is indexed by a unique key.
Syntax
Dictionary = {'key1': 'value1','key2': 'value2',...,'keyn': 'valuen'}
Example
X= {'a' :"apple", 'b' :"ball", 'c' :"cat"}
print(X)
Output
{'a' :'apple', 'b' :'ball', 'c' :'cat'}
In the above example, we have created a list where each alphabet maps a English word i.e., keys are in characters (alphabets) and values are in strings.
Create an empty dictionary
We can create a dictionary using built-in function dict(), which creates a new dictionary with no items. We can also create dictionary using {}.
Example
alphabets = dict()
print(alphabets)
Output
{}
Where, {} represents empty dictionary.
Initialize and access the elements of a dictionary
To initialize or add an item to the dictionary, square brackets with unique keys are used.
Example
# Creating an empty dictionary
alphabets = dict()
# Adding elements
alphabets['a']="apple"
alphabets['b']="ball"
alphabets['c']="cat"
alphabets['e']="elephant"
alphabets['d']="dog"
# Printing the dictionary
print("alphabets:",alphabets)
# Accessing elements by keys
print("Accessing elements by keys...")
print("alphabets['a']:", alphabets['a'])
print("alphabets['b']:", alphabets['b'])
print("alphabets['c']:", alphabets['c'])
print("alphabets['d']:", alphabets['d'])
print("alphabets['e']:", alphabets['e'])
Output
alphabets: {'a': 'apple', 'b': 'ball', 'c': 'cat', 'e': 'elephant', 'd': 'dog'}
Accessing elements by keys...
alphabets['a']: apple
alphabets['b']: ball
alphabets['c']: cat
alphabets['d']: dog
alphabets['e']: elephant
Note: May you observe the order of the key-value pairs is not in same order (i.e., input and output orders are not same). Because the order of items in a dictionary is unpredictable.
Traverse/Iterate through a dictionary
Traversing refers to visiting each element index at least one to access its value. This can be done using looping or say by using 'for-loop'.
Example
# Creating an empty dictionary
alphabets = dict()
# Adding elements
alphabets['a']="apple"
alphabets['b']="ball"
alphabets['c']="cat"
alphabets['e']="elephant"
alphabets['d']="dog"
# Printing the dictionary
print("alphabets:",alphabets)
# Traverse/Iterate through a dictionary
print("\nTraverse/Iterate through a dictionary...")
for alphabet in alphabets:
print(alphabets[alphabet])
Output
alphabets: {'a': 'apple', 'b': 'ball', 'c': 'cat', 'e': 'elephant', 'd': 'dog'}
Traverse/Iterate through a dictionary...
apple
ball
cat
elephant
dog
As said previously, the order of items in a dictionary is unpredictable.
Length of a dictionary
To find the length of a dictionary i.e., the total number of elements of a dictionary, use the len() method. It returns the total number of elements of a dictionary.
Example
# Creating dictionary
alphabets = {"a": "apple", "b": "ball", "c": "cat", "d": "dog"}
# Printing the dictionary
print("alphabets:", alphabets)
# Length of the dictionary
print("The total elements are:", len(alphabets))
Output
alphabets: {'a': 'apple', 'b': 'ball', 'c': 'cat', 'd': 'dog'}
The total elements are: 4
Create dictionary using the dict() constructor
A dictionary can also be created using the dict() constructor by providing the keys and values.
Example
# Creating dictionary
alphabets = dict(a="apple", b="ball", c="cat", d="dog")
# Printing the dictionary
print("alphabets:", alphabets)
Output
alphabets: {'a': 'apple', 'b': 'ball', 'c': 'cat', 'd': 'dog'}
Dictionary with items of different data types
A dictionary can also have items of different data types such as strings, integers, Booleans, etc. It may also have a dictionary itself.
Example
# Creating dictionary with different items
# of different data types
student = {
"rollNo": 101,
"name": "Raghav",
"perc": 85.90,
"isMonitor": False,
"dob": {"dd": 10, "mm": 7, "yy": 2002},
}
# Printing the dictionary
print("student:", student)
Output
student: {'rollNo': 101, 'name': 'Raghav', 'perc': 85.9, 'isMonitor': False, 'dob': {'dd': 10, 'mm': 7, 'yy': 2002}}
Type of dictionary and its items
The type of a dictionary is <class 'dict'> that can be found using the type() method. In the below example, we will print the type of the dictionary and its items.
Example
# Creating dictionary with different items
# of different data types
student = {
"rollNo": 101,
"name": "Raghav",
"perc": 85.90,
"isMonitor": False,
"dob": {"dd": 10, "mm": 7, "yy": 2002},
}
# Printing the dictionary
print("student:", student)
print()
# Printing types
print("Type of student:", type(student))
print("Type of student['rollNo']:", type(student['rollNo']))
print("Type of student['name']:", type(student['name']))
print("Type of student['perc']:", type(student['perc']))
print("Type of student['isMonitor']:", type(student['isMonitor']))
print("Type of student['dob']:", type(student['dob']))
Output
student: {'rollNo': 101, 'name': 'Raghav', 'perc': 85.9, 'isMonitor': False, 'dob': {'dd': 10, 'mm': 7, 'yy': 2002}}
Type of student: <class 'dict'>
Type of student['rollNo']: <class 'int'>
Type of student['name']: <class 'str'>
Type of student['perc']: <class 'float'>
Type of student['isMonitor']: <class 'bool'>
Type of student['dob']: <class 'dict'>