Python dictionary is an unordered collection of items.
The collections we have studied till now like list , tuple and string are all ordered collections as well as can hold only one value as their element
On the other hand dictionary is an unordered collection which holds the data in a key: value pair.
Sometimes we need to store the data so that one piece of information is connected to another piece of information.
For example
RollNo >Student Name or
Customer Name >Mobile Number
In these examples RollNo will be called a key while it’s associated Student Name will be called value
To store such paired data Python provides us the data type called dictionary
Creating a dictionary is as simple as placing items inside curly braces { } separated by comma.
Every item has a key and the corresponding value expressed as a pair, key: value.
While values can be of any data type and can repeat, but keys must be of immutable type and must be unique.
d = {
<key>: <value>,
<key>: <value>,
. . .
<key>: <value>
}
# empty dictionary
my_dict = { }
# dictionary with integer keys
my_dict = {1: 'Chitranshi', 2: 'Aditi',3:'Akansha'}
# dictionary with mixed keys
my_dict = {1: 'Adarsh', 'a':'vowel'}
# dictionary with list as values
my_dict = {'Rahul':['C', 'C++'], 'Ajay':['Java', 'C', 'Python'], 'Neeraj':['Oracle', 'Python']}
Important points We also can create a list by using the dict( ) function
# Create an empty dictionary
my_dict = dict()
# Create a dictionary with elements
my_dict = dict({1:'apple', 2:'ball'})
# Create a dictionary with other sequences
my_dict = dict([(1,'apple'), (2,'ball')])
We can print a dictionary in four ways:
1. Directly passing it to the print( ) function
2. Accessing individual values by passing keys to subscript operator [ ]
3. Accessing individual values by passing keys to the method get( )
4. Traversing using loop
student_data = {1:'Chitranshi', 2:'Aditi',3:'Akansha', 4:'Supriya',5:'Adarsh'}
print(student_data)
Output:
{1: 'Chitranshi', 2: 'Aditi', 3: 'Akansha', 4: 'Supriya', 5: 'Adarsh'}
As mentioned previously, keys are used to retrieve their corresponding values in Python dictionary.
Keys can be used inside subscript operator [ ] or we can use Python built-in method get() to access the values in the dictionary using keys.
Accessing individual element:
student_data = {1: 'Chitranshi', 2: 'Aditi', 3: 'Akansha', 4: 'Supriya', 5: 'Adarsh'}
print(student_data[3])
print(student_data.get(3))
Output
Akansha
Akansha
Difference between [] and get() Python allows us three ways to traverse over a dictionary:
Iterate only on keys
Iterate on both , keys and values
Iterate only on values
Since dictionary is mutable, so we can add new items or change the value of existing items using either of two ways.
These are:
assignment operator or
update( ) method of dictionary object
Updating using assignment operator
Syntax Of Assigment Operator:
dict_var[key]=value
When we use assignment operator , Python simply searches for the key in the dictionary object.
dict_var.update( dict_var2)
The update( ) method merges the keys and values of one dictionary into another, overwriting values of the same key
dict_var.pop(key,[default])
The pop() method takes two parameters:
Just like list , Python also allows us to delete an item from the dictionary by calling the operator/keyword del
Syntax Of del Operator:
del dict_var[key]
It removes the entry from the dictionary whose key is passed as argument
dict_var.clear( )
The clear() method doesn’t take any argument
Like list , Python allows us to use the following functions with dictionary object
len()
max()
min()
any()
all()
sorted()
dict()
len() | returns the number of items in the dictionary |
---|---|
max() | Returns the greatest key present in the dictionary |
min() | Returns the least item present in the dictionary |
any() | Like list and tuple , any( ) function accepts a dict as argument and returns True if atleast one element of the dict is True. If not, this method returns False. If the dict is empty, then also it returns False |
all() | The all( ) function accepts a dict as argument and returns True if all the keys of the dict are True or if the List is empty .If not, this method returns False. |
sorted() | Like it is with lists and tuples, the sorted() function returns a sorted sequence of the keys in the dictionary. The sorting is in ascending order, and doesn’t modify the original Python dictionary. |
dict() | dict( ) function can be used to create dictionaries . It can accept key-value pairs or iterable or mappings as argument and converts them into dictionaries |
Python provides us following methods to work upon dictionary object:
clear()
copy()
get()
items()
keys()
pop()
update()
values()
The copy() method
This method returns a shallow copy of the dictionary.
Syntax:
dict.copy()
Dictionary Comprehension is a mechanism for transforming one dictionary into another dictionary.
During this transformation, items within the original dictionary can be conditionally included in the new dictionary and each item can be transformed as needed.
Syntax:
dict_variable = { key:value for (key,value) in iterable}
Explanation
cars = {"Maruti":"Ciaz","Hyundai":"Verna","Honda":"Amaze"}
newcars={ k:v for (k,v) in cars.items()}
print(newcars)
Output:
{'Maruti': 'Ciaz', 'Hyundai': 'Verna', 'Honda': 'Amaze'}
Like list comprehension , dictionary comprehension also allows us to add conditionals to make it more powerful.
Syntax:
dict_variable = { key:value for (key,value) in iterable <test_cond>}
As usual , only those key-value pairs will be returned by dictionary comprehension which satisfy the condition
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
dict2 = {k:v*2 for (k,v) in dict1.items() if v>2}
print(dict2)
Output:
{'c': 6, 'd': 8, 'e': 10}
Almost any type of value can be used as a dictionary key in Python , like integer, float, Boolean etc
We can even use built-in objects like types and functions
Duplicate keys are not allowed. If we assign a value to an already existing dictionary key, it does not add the key a second time, but replaces the existing value
If we specify a key a second time during the initial creation of a dictionary, the second occurrence will override the first
A dictionary key must be of a type that is immutable. Like integer, float, string and Boolean—can serve as dictionary keys. Even a tuple can also be a dictionary key, because tuples are immutable
However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable
There are no restrictions on dictionary values.
A dictionary value can be any type of object Python supports, including mutable types like lists and dictionaries, and user-defined objects
There is also no restriction against a particular value appearing in a dictionary multiple times