A Python dictionary is a data structure that stores key/value pairs to provide information about the structure. This article will teach you all you need to know about the concept of Python dictionary, including how they are constructed, how the elements are accessed, added, and removed from dictionaries, and how to use various built-in methods.
Python Dictionary
In Python, the dictionary is a data type that may replicate a real-world data arrangement in which a specific value exists for a specified key. A dictionary in Python is an unordered collection of data elements. A dictionary item has a key/value pair. A colon (:) separates each key from its value, commas divide the elements, and curly braces surround the entire thing. Keys are distinct within a dictionary, although values may or may not be. A dictionary’s contents can be of any type, but its keys must be of an immutable data type, such as strings, numbers, or tuples. When the key is known, dictionaries are optimized to retrieve values.
Because dictionaries do not retain their information in any specific sequence, you may not receive your information in the same order that you entered it. An empty dictionary with no items is written with only two curly braces, as shown here: {}.
Creating a Python Dictionary
A Dictionary can be formed in Python by assigning a sequence of entries enclosed by curly braces {} and separated by a comma. Dictionary stores a pair of values, one of which is the Key and the other being the key:value pair element. While values can be of any data type and repeated, keys must be immutable (string, number, or tuple with immutable elements) and unique, i.e. they cannot be repeated.
The general syntax followed to create Python dictionary is as follows:
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}
Or Python dictionary can be created using the dict() in-built function provided by Python.
For example
# Python program to create a dictionary
# empty dictionary
my_dict = {}
print(my_dict)
# dictionary with keys as integers
my_dict = {1: 'One', 2: 'Two', 3: 'Three'}
print(my_dict)
# dictionary with mixed keys
my_dict = {'Name': 'John', 'Age': 24, 1: [2, 4, 3]}
print(my_dict)
# using dict()
my_dict = dict({1:'One', 2:'Two'})
print(my_dict)
# from sequence having each item as a pair
my_dict = dict([(1,'John'), (2,'David')])
print(my_dict)
Output
{}
{1: 'One', 2: 'Two', 3: 'Three'}
{'Name': 'John', 'Age': 24, 1: [2, 4, 3]}
{1: 'One', 2: 'Two'}
{1: 'John', 2: 'David'}
Accessing Elements from Dictionary
Because Dictionaries are an unordered collection of iterables, a value within it cannot be accessed using an index; instead, a key must be supplied in square brackets. Keys can be used with either square brackets [] or the get() method.
If we use square brackets [], we get a KeyError if a key is not found in the dictionary. The get() method, on the other hand, returns None if the key is not found.
Example
# Python program to access elements from a dictionary
my_dict = {'Name': 'Sean', 'Age': 24, 'Hobby': 'Dancing', 'City': 'NY'}
# using square brackets
print(my_dict['Name'])
print(my_dict['Age'])
# using get() method
print(my_dict.get('Hobby'))
# key not found
print(my_dict.get('Salary'))
# error raised when key not found
print(my_dict['Occupation'])
Output
Sean
24
Dancing
None
Traceback (most recent call last):
 File "", line 15, in
KeyError: 'Occupation'
Changing and Adding Dictionary elements
Dictionaries are subject to change. Using an assignment operator, we can add new things or change the value of existing items. By declaring value together with the key, for example, Dict[Key] = ‘Value’, one value at a time can be added to a Dictionary. Another approach is to use Python’s update() function.
Note – Â If the key-value pair is already in the dictionary, the value is updated. In the absence of this, a new key:value pair is added to the dictionary.
Example
# Python program to update/add elements in a dictionary
my_dict = {'Car': 'Audi', 'Bike': 'Honda'}
print('Original Dictionary:', my_dict)
# updating value of an existing key
my_dict['Bike'] = 'Ducati'
print('Updated Dictionary:', my_dict)
# adding new value
my_dict['Plane'] = 'Boeing'
print('Updated Dictionary:', my_dict)
Output
Original Dictionary: {'Car': 'Audi', 'Bike': 'Honda'}
Updated Dictionary: {'Car': 'Audi', 'Bike': 'Ducati'}
Updated Dictionary: {'Car': 'Audi', 'Bike': 'Ducati', 'Plane': 'Boeing'}
Removing elements from Dictionary
A key can be removed from a dictionary in three ways: from an individual entry, from all entries, or from the entire dictionary.
- The pop() function can be used to remove a single element. The value of the key that has been specified to be eliminated is returned by the pop() function.
- To randomly remove any elements (key-value pairs) of the dictionary, we can use the popitem() It returns the arbitrary key-value pair that has been removed from the dictionary.
- Using the clear() method, all elements can be eliminated at once.
- The del keyword is used to completely delete the entire dictionary.
Example
# Python program to remove/delete elements from a dictionary
my_dict = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five'}
print('Original Dictionary:', my_dict)
# removing single element
print(my_dict.pop(4))
print('Updated Dictionary:', my_dict)
# adding new value
print(my_dict.popitem())
print('Updated Dictionary:', my_dict)
# remove all items
my_dict.clear()
print(my_dict)
# delete the dictionary itself
del my_dict
print(my_dict)
Output
Original Dictionary: {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five'}
Four
Updated Dictionary: {1: 'One', 2: 'Two', 3: 'Three', 5: 'Five'}
(5, 'Five')
Updated Dictionary: {1: 'One', 2: 'Two', 3: 'Three'}
{}
Traceback (most recent call last):
 File "", line 19, in
NameError: name 'my_dict' is not defined
Python Dictionary Methods
The Python dictionary provides a variety of methods and functions that can be used to easily perform operations on the key-value pairs. Python dictionary methods are listed below.
Method | Description |
clear() | Removes all the elements from the dictionary |
copy() | Returns a shallow copy of the specified dictionary |
fromkeys(seq, val) | Creates a new dictionary with keys from seq and val assigned to all the keys |
get(key) | Returns the value of the specified key |
has_key() | Returns True if the key exists in the dictionary, else returns False |
items() | Returns a list of dictionary’s items in (key, value) format pairs |
keys() | Returns a list containing all the keys in the dictionary |
pop(key) | Removes and returns an element from a dictionary having the given key |
popitem() | Removes and returns an arbitrary item (key, value). |
setdefault(key, val) | Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of val |
update() | Updates the dictionary by adding key-value pair |
values() | Returns a list containing all the values in the dictionary |
Let us look at few examples of these Python dictionary methods.
# Dictionary Methods
my_dict = {}
age = my_dict.fromkeys(['John', 'Emily', 'Tina'], 20)
print(age)
print('Keys in the dictionary are:', list(age.keys()))
print('Values in the dictionary are:', list(age.values()))
print('Age value of John:', age.get('John'))
Output
{'John': 20, 'Emily': 20, 'Tina': 20}
Keys in the dictionary are: ['John', 'Emily', 'Tina']
Values in the dictionary are: [20, 20, 20]
Age value of John: 20
Python Dictionary Comprehension
In Python, dictionary comprehension is a simple and beautiful approach to generate a new dictionary from an iterable. Dictionary comprehension is made up of an expression pair (key: value) followed by a for statement enclosed in curly braces. Here’s an example of a dictionary where each item is a pair of a number and its square.
Example
# Dictionary Comprehension
multiple = {x: x*2 for x in range(5)}
print(multiple)
Output
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
The above code is equivalent to:
multiple = {}
for x in range(5):
   multiple[x] = x*2
print(multiple)
Output
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
Other Dictionary Operations
-
Dictionary Membership Test
What if we want to check if a specific key is present in the dictionary? Using the keyword ‘in’ and ‘not in’, we can determine whether a key is in a dictionary or not. It’s worth noting that the membership test only applies to keys, and not values.
Example
# Membership Test for Dictionary Keys
results = {'Sam': 'Pass', 'Zac': 'Pass', 'Lily': 'Fail', 'Casey': 'Pass'}
print('Lily' in results)Â Â # returns True
print('Rocky' in results)Â # returns False
print('Ella' not in results)Â # returns True
# membership tests for key only not value, returns False
print('Pass' in results)
Output
True
False
True
False
-
Iterating Through a Dictionary
Using a for loop, we can traverse through each key, value or both in a dictionary. For example,
# Iterating through a Dictionary
course = {'Sam': 'MBA', 'Zac': 'MS', 'Lily': 'BBA', 'Casey': 'Architecture'}
for i in course:
   print(course[i])
print('')
# printing keys and values
for i,j in course.items():
   print(i, '->', j)
Output
MBA
MS
BBA
Architecture
Sam -> MBA
Zac -> MS
Lily -> BBA
Casey -> Architecture
-
Dictionary Built-in Functions
Built-in functions such as all(), any(), len(), cmp(), sorted(), and others are frequently used with Python dictionaries to complete various tasks.
Function | Description |
all() | Returns value True if all the keys in the dictionary are true or if the dictionary is empty |
any() | Returns True if any of the key in the dictionary is True. If the dictionary is empty it returns False |
len() | Returns the number of items in the dictionary |
cmp() | Used to compare items of 2 dictionaries |
sorted() | Returns a sorted list of keys in the dictionary |
Example
# Dictionary Built-in Functions
my_dict = {0: 'Zero', 1: 'One', 2: 'Two', 3: 'Three'}
print(all(my_dict))
print(any(my_dict))
print(len(my_dict))
print(sorted(my_dict))
Output
False
True
4
[0, 1, 2, 3]
Frequently Asked Questions
Q1. What is a Python dictionary?
In Python, a dictionary is a data structure that stores key/value pairs to provide information about the structure. In Python, the dictionary is a data type that may replicate a real-world data arrangement in which a specific value exists for a specified key. A dictionary in Python is an unordered collection of data elements. A dictionary item has a key/value pair. A colon (:) separates each key from its value, commas divide the elements, and curly braces surround the entire thing.
Q2. How do you declare a dictionary in Python?
A Dictionary can be formed in Python by assigning a sequence of entries enclosed by curly braces {} and separated by a comma. Dictionary stores a pair of values, one of which is the Key and the other being the key:value pair element. While values can be of any data type and repeated, keys must be immutable (string, number, or tuple with immutable elements) and unique, i.e. they cannot be repeated. Or Python dictionary can be created using the dict() in-built function provided by Python.
Example
my_dict = {1: 'One', 2: 'Two', 3: 'Three'}
print(my_dict)
# dictionary with mixed keys
my_dict = {'Name': 'Daisy', 'Salary': 35000, 1: [2, 4, 3]}
print(my_dict)
# using dict()
my_dict = dict({1:'One', 2:'Two'})
print(my_dict)
Output
{1: 'One', 2: 'Two', 3: 'Three'}
{'Name': 'Daisy', 'Salary': 35000, 1: [2, 4, 3]}
{1: 'One', 2: 'Two'}
Q3. Is dictionary faster than lists in Python?
Dictionary is any time faster than a list in Python.
The dictionary employs a hash lookup, whereas the list necessitates traveling through the list till it finds the result from beginning to end each time.
Another method of saying it is Because there is nothing to look up, the list will be faster than the dictionary on the first item. It’s the first item, and it’s finished. However, the list must go through the first item, then the second item the second time. It has to go through the first thing, then the second item, then the third item… and so on. As a result, the lookup takes longer and longer with each iteration. The longer it takes, the longer the list. While the dictionary has a more or less constant lookup time. And hence the dictionary is much faster than lists in Python.
Q4. How do you access a dictionary in Python?
Because Dictionaries are an unordered collection of iterables, a value within it cannot be accessed using an index; instead, a key must be supplied in square brackets. Keys can be used with either square brackets [] or the get() method.
Example
# Python program to access elements from a dictionary
my_dict = {'Name': 'Sean', 'Age': 24, 'Hobby': 'Dancing', 'City': 'NY'}
# using square brackets
print(my_dict['Name'])
print(my_dict['Age'])
# using get() method
print(my_dict.get('Hobby'))
# key not found
print(my_dict.get('Salary'))
# error raised when key not found
print(my_dict['Occupation'])
Output
Sean
24
Dancing
None
Traceback (most recent call last):
 File "", line 15, in
KeyError: 'Occupation'
Leave a Reply