python


Dictionary


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


How to create a 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.


General Syntax for creating a dictionary

Syntax:

d = { 
        <key>: <value>, 
        <key>: <value>, 
        . . . 
        <key>: <value> 
       }


How to create a dictionary?


# 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
The important characteristics of Python dictionaries are as follows:
They can be nested.
They are mutable.
They are dynamic.
They are unordered.
Unlike Lists and tuples , a dictionary item is accessed by it’s corresponding key not index


Other ways of creating a dictionary

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')])


Printing the dictionary

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


Printing the entire dictionary


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'}

Accessing Individual Element

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()
Although both subscript operator and get( ) method allow us to access individual element using it’s key , but there is an important difference in them.
The difference is that when we try to access a value whose key doesn’t exist in the dictionary using subscript operator , it throws a KeyError.
But when we try to access using get() method, instead of throwing KeyError, it returns nothing which in Python is None.


Traversing a dictionary

Python allows us three ways to traverse over a dictionary:
Iterate only on keys
Iterate on both , keys and values
Iterate only on values


Updating a dictionary

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.
If the key is found , it’s value is replaced with the value we have passed, otherwise a new key-value pair entry is created
Updating using update() method Syntax Of update( ) Method:

dict_var.update( dict_var2)
The update( ) method merges the keys and values of one dictionary into another, overwriting values of the same key


Removing data from dictionary

Since dictionary is mutable, so we can remove items from the dictionary.
There are certain methods available in Python to delete the items or delete entire dictionary.
These are:
pop(key): removes the entry with provided key and returns it’s valueb
del: deletes a single item or the dictionary entirely
clear(): clears all the items in the dictionary and returns an empty dictionary
The pop() method
Syntax Of pop( ) Method:

dict_var.pop(key,[default])
The pop() method takes two parameters:
key - key which is to be searched for removal
default - (optional) value which is to be returned when the key is not in the dictionary Return Value From pop( )
If key is found – it returns value of removed/popped element from the dictionary
If key is not found – it returns the value specified as the second argument (default)
If key is not found and default argument is not specified – it raises  KeyError exception
The del Operator

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
If the key is not found or dictionary is empty it raises KeyError exception
If we do not pass the key then del deletes the entire dictionary object
The clear() method
The clear() method removes all items from the dictionary.
Syntax Of clear( ) Method:

dict_var.clear( )
The clear() method doesn’t take any argument
It returns nothing ( None )


Functions used with dictionary

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


Dictionary Methods

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

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
Iterable can be any object on which iteration is possible
(key,value) is the tuple which will receive these key-value pairs one at a time
key:value is the expression or key-value pair which will be assigned to new dictionary
Example: program to produce a copy of the dictionary cars using dictionary comprehension

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'}


Adding conditions to dictionary comprehensions

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
Example: Write a program to produce a new dictionary from the given dictionary but with the values that are greater than 2 and store their doubles

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}


Restrictions on dictionary keys

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


Restrictions on dictionary values

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