Dictionaries in Python
Dictionaries in Python
In Python version 3.7 and onwards, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are unordered.
For example, consider the Phone lookup, where it is very easy and fast to find
the phone number(value) when we know the name (Key) associated with it.
Dictionaries in Python:
Characteristics of dictionaries
Creating a dictionary
There are following three ways to create a dictionary.
Example:
Empty Dictionary
When we create a dictionary without any elements inside the curly brackets
then it will be an empty dictionary.
emptydict = {}
print(type(emptydict))
# Output class 'dict'
Note:
1. Retrieve value using the key name inside the [] square brackets
2. Retrieve value by passing key name as a parameter to
the get() method of a dictionary.
Example
As we can see in the output, we retrieved the value ‘Jessa’ using key ‘name”
and value 1178 using its Key ‘telephone’.
Use the following dictionary methods to retrieve all key and values at once
Method Description
items() Returns all the items present in the dictionary. Each item will be inside a tuple as a key-value pair.
We can assign each method’s output to a separate variable and use that for
further computations if required.
Example
Iterating a dictionary
We can iterate through a dictionary using a for-loop and access the individual
keys and their corresponding values. Let us see this with an example.
Output
key : value
name : Jessa
country : USA
telephone : 1178
key : value
name Jessa
country USA
telephone 1178
Example
Note: We can also add more than one key using the update() method.
Example
Using the setdefault() method default value can be assigned to a key in the
dictionary. In case the key doesn’t exist already, then the key will be inserted
into the dictionary, and the value becomes the default value, and None will be
inserted if a value is not mentioned.
In case the key exists, then it will return the value of a key.
Example
# Display dictionary
for key, value in person_details.items():
print(key, ':', value)
Output
name : Jessa
country : USA
telephone : 1178
state : Texas
zip : None
Note: As seen in the above example the value of the setdefault() method has
no effect on the ‘country’ as the key already exists.
• Using key name: We can directly assign new values by using its
key name. The key name will be the existing one and we can
mention the new value.
• Using update() method: We can use the update method by
passing the key-value pair to change the value. Here the key name
will be the existing one, and the value to be updated will be new.
Example
Method Description
pop(key[,d]) Return and removes the item with the key and return its value. If the key is not found, it raises K
Return and removes the last inserted item from the dictionary. If the dictionary is empty, it
popitem()
raises KeyError.
del key The del keyword will delete the item with the key that is passed
clear() Removes all items from the dictionary. Empty the dictionary
del
Delete the entire dictionary
dict_name
Now, Let’s see how to delete items from a dictionary with an example.
Example
person = {'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50,
'height': 6}
In this method, we can just check whether our key is present in the list of keys
that will be returned from the keys() method.
Let’s check whether the ‘country’ key exists and prints its value if found.
Let’s see how to merge the second dictionary into the first dictionary
Example
As seen in the above example the items of both the dictionaries have been
updated and the dict1 will have the items from both the dictionaries.
Using **kwargs to unpack
We can unpack any number of dictionary and add their contents to another
dictionary using **kwargs. In this way, we can add multiple length arguments to
one dictionary in a single statement.
As seen in the above example the values of all the dictionaries have been
merged into one.
Note: One thing to note here is that if both the dictionaries have a common
key then the first dictionary value will be overridden with the second
dictionary value.
Example
As mentioned in the case of the same key in two dictionaries the latest one
will override the old one.
In the above example, both the dictionaries have the key ‘Emma’ So the value
of the second dictionary is used in the final merged dictionary dict1.
Copy a Dictionary
We can create a copy of a dictionary using the following two ways
Note: When you set dict2 = dict1, you are making them refer to the same dict
object, so when you modify one of them, all references associated with that
object reflect the current state of the object. So don’t use the assignment
operator to copy the dictionary instead use the copy() method.
Example
print(dict1)
# Output {'Jessa': 90, 'Emma': 55}
Nested dictionary
Nested dictionaries are dictionaries that have one or more dictionaries as their
members. It is a collection of many dictionaries in one dictionary.
Example
# Display dictionary
print("person:", person)
Output
person: {'name': 'Jessa', 'company': 'Google', 'address': {'state': 'Texas',
'city': 'Houston'}}
City: Houston
Person details
name: Jessa
company: Google
Person Address
state: Texas
city : Houston
As we can see in the output we have added one dictionary inside another
dictionary.
In this example, we will create a separate dictionary for each student and in
the end, we will add each student to the ‘class_six’ dictionary. So each student
is nothing but a key in a ‘class_six’ dictionary.
In order to access the nested dictionary values, we have to pass the outer
dictionary key, followed by the individual dictionary key.
We can iterate through the individual member dictionaries using nested for-
loop with the outer loop for the outer dictionary and inner loop for retrieving
the members of the collection.
Example
Output
Student 3 marks: 85
Class details
student1
name: Jessa
state: Texas
city: Houston
marks: 75
student2
name: Emma
state: Texas
city: Dallas
marks: 60
student3
name: Kelly
state: Texas
city: Austin
marks : 85
Sort dictionary
The built-in method sorted() will sort the keys in the dictionary and returns a
sorted list. In case we want to sort the values we can first get the values using
the values() and then sort them.
Example
Dictionary comprehension
Dictionary comprehension is one way of creating the dictionary where the
values of the key values are generated in a for-loop and we can filter the items
to be added to the dictionary with an optional if condition. The general syntax
is as follows
# calculate the square of each even number from a list and store in dict
numbers = [1, 3, 5, 2, 8]
even_squares = {x: x ** 2 for x in numbers if x % 2 == 0}
print(even_squares)
Here in this example, we can see that a dictionary is created with an input list
(any iterable can be given), the numbers from the list being the key and the
value is the square of a number.
We can even have two different iterables for the key and value and zip them
inside the for loop to create a dictionary.
As the name suggests the max() and min() functions will return the keys with
maximum and minimum values in a dictionary respectively. Only the keys are
considered here not their corresponding values.
dict = {1:'aaa',2:'bbb',3:'AAA'}
print('Maximum Key',max(dict)) # 3
print('Minimum Key',min(dict)) # 1
As we can see max() and min() considered the keys to finding the maximum and
minimum values respectively.
all()
When the built-in function all() is used with the dictionary the return value
will be true in the case of all – true keys and false in case one of the keys is
false.
#empty dictionary
dict3= {}
Output
any()
any()function will return true if dictionary keys contain anyone false which
could be 0 or false. Let us see what any() method will return for the above
cases.
#empty dictionary
dict3= {}
#all false
dict5 = {0:False}
Output
As we can see this method returns true even if there is one true value and one
thing to note here is that it returns false for empty dictionary and all false
dictionary.
Dictionaries are items stored in Key-Value pairs that actually use the mapping
format to actually store the values. It uses hashing internally for this. For
retrieving a value with its key, the time taken will be very less as O(1).
For example, consider the phone lookup where it is very easy and fast to find
the phone number (value) when we know the name (key) associated with it.
Operations Description
d1.items() Returns a list of all the items in the dictionary with each key-value pair insid
max(d1) Returns the key with the maximum value in the dictionary d1
min(d1) Returns the key with the minimum value in the dictionary d1