12.Dictionary In Python
What is Dictionary?
Python Dictionary is used to store the data in a key-value pair format. The dictionary is the data type in Python, which can simulate the real-life data arrangement where some specific value exists for some particular key. It is the mutable data-structure. The dictionary is defined into element Keys and values.
Keys must be an immutable element.
Value can be any type such as list, tuple, integer, etc.
In other words, we can say that a dictionary is the collection of key-value pairs where the value can be any Python object. In contrast, the keys are the immutable Python object, i.e., Numbers, string, or tuple.
A Dictionary is enclosed under curly braces {}. For Example:
In [1]:
employee = {"name" : "Abhi",
"role" : "Trainer",
}
print(employee)
{'name': 'Abhi', 'role': 'Trainer'}
In above dictionary , Key 'name' holds 'Abhi' value .
Keys Must be immutable:
Keys in Dictionary must be immutable elements like numbers , strings , tuple etc. It will throw an error if key is a mutable element.
Properties of a Dictionary :
Ordered :
Dictionaries do not have index numbers but still it has keys, hence dictionaries are ordered. For Example:
In [2]:
employee = {"name" : "Abhi",
"role" : "Trainer",
}
print(employee)
{'name': 'Abhi', 'role': 'Trainer'}
Mutable:
Dictionaries are mutable or changeable. We can change values of dictionary elements with the help of keys. For Example :
In [3]:
employee = {"name" : "Abhi",
"role" : "Trainer",
}
employee['name'] = "Smith"
print(employee)
{'name': 'Smith', 'role': 'Trainer'}
Does not allow duplicate Keys:
If there is more than one key-value pair with same key , Dictionary will store only last inserted Key-Value pair. For Example:
In [5]:
employee = {"name" : "Abhi",
"name" : "Abhishek",
"role" : "Trainer",
}
print(employee)
{'name': 'Abhishek', 'role': 'Trainer'}
Functions used in Dictionaries :
Functions like max() , min() and len() works on sequence .
In [6]:
employee = {"name" : "Abhi",
"role" : "Trainer",
}
max(employee) #max() works on keys.
In [7]:
employee = {"name" : "Abhi",
"role" : "Trainer",
}
min(employee) #min() works on keys.
In [9]:
employee = {"name" : "Abhi",
"role" : "Trainer",
}
len(employee)
How to access values from a dictionary :
We can access values of dictionary with the help of keys , same as we do with the help of index in list.
In [10]:
employee = {"name" : "Abhi",
"role" : "Trainer",
}
value = employee["role"]
print(value)
How to change values in a dictionary :
To change value of a dictionary we will simply assign new value to its key. For Example:
In [11]:
employee = {"name" : "Abhi",
"role" : "Trainer",
}
employee['role'] = "Senior Trainer"
print(employee)
{'name': 'Abhi', 'role': 'Senior Trainer'}
How to add values in a Dictionary :
We can add values in a dictionary simply by assigning a new value in a new key. For Example :
In [12]:
employee = {"name" : "Abhi",
"role" : "Trainer",
}
employee["Course"] = "Data Science"
print(employee)
{'name': 'Abhi', 'role': 'Trainer', 'Course': 'Data Science'}
Dictionary Methods :
Functions that are specific to dictionary are known as dictionary methods. We will go through each method one by one.
keys() :
keys() method return a sequence of keys. For example :
In [13]:
employee = {"name" : "Abhi",
"role" : "Trainer",
}
k = employee.keys()
print(k)
dict_keys(['name', 'role'])
values():
values() method return a sequence of values. For Example:
In [14]:
employee = {"name" : "Abhi",
"role" : "Trainer",
}
k = employee.values()
print(k)
dict_values(['Abhi', 'Trainer'])
items() :
items() method returns tuple of key-value pairs in a sequence. For Example:
In [15]:
employee = {"name" : "Abhi",
"role" : "Trainer",
}
i = employee.items()
print(i)
dict_items([('name', 'Abhi'), ('role', 'Trainer')])
Iteration in keys of dictionaries:
Below example is to show you how to iterate keys of dictionaries :
In [16]:
employee = {"name" : "Abhi",
"role" : "Trainer",
"course" : "data science",
"duration" : 3
}
for k in employee.keys():
print(k)
name
role
course
duration
We can also iterate keys of dictionaries simply iterating dictionary only. For Example:
In [17]:
employee = {"name" : "Abhi",
"role" : "Trainer",
"course" : "data science",
"duration" : 3
}
for k in employee.keys():
print(k)
name
role
course
duration
Iteration in values of dictionaries:
employee = {"name" : "Abhi",
"role" : "Trainer",
"course" : "data science",
"duration" : 3
}
for v in employee.values():
print(v)
Abhi
Trainer
data science
3
Iteration of key-value pair or items in dictionaries:
Below example is to show you how to iterate key-value pair or items in dictionaries . It returns a tuple.
In [19]:
employee = {"name" : "Abhi",
"role" : "Trainer",
"course" : "data science",
"duration" : 3
}
for i in employee.items():
print(i)
('name', 'Abhi')
('role', 'Trainer')
('course', 'data science')
('duration', 3)
We can also separate keys and values from with the help of this code.
In [22]:
employee = {"name" : "Abhi",
"role" : "Trainer",
"course" : "data science",
"duration" : 3
}
for k,v in employee.items(): #k holds keys and v holds values.
print(f'{k} holds {v}')
name holds Abhi
role holds Trainer
course holds data science
duration holds 3
How to create dictionary with user inputs:
To create a dictionary with user inputs , we may ask keys and values from user and add them in an empty dictionary. For Example:
In [23]:
mydict = {}
for i in range(5):
k = input("Enter Key : ")
v = input("Enter Values : ")
mydict[k] = v
print(mydict)
Enter Key : name
Enter Values : abhi
Enter Key : role
Enter Values : trainer
Enter Key : course
Enter Values : data science
Enter Key : duration
Enter Values : 3
Enter Key : projects
Enter Values : 50
{'name': 'abhi', 'role': 'trainer', 'course': 'data science', 'duration': '3', 'projects': '50'}
how to add an iterables items in a dictionaries: update()
update() method adds items (key value pair) from an iterable in a dictionary. For Example:
In [24]:
thisdict = {'name': 'abhi',
'role': 'trainer',
'course': 'data science',
'duration': '3',
'projects': '50'
}
anotherdict = {"company" : "console flare",
"location" : "Noida"
}
thisdict.update(anotherdict)
print(thisdict)
{'name': 'abhi', 'role': 'trainer', 'course': 'data science', 'duration': '3', 'projects': '50', 'company': 'console flare', 'location': 'Noida'}
You can also update items from list or tuple or sets in a dictionary. But the only condition is it should be in key value form. A simple list cannot be converted in a dictionary. For Example :
In [2]:
thisdict = {'name': 'abhi',
'role': 'trainer',
'course': 'data science'
}
thislist = [1,2,3,4,5]
thisdict.update(thislist)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-6bd84fe955ce> in <module>
5
6 thislist = [1,2,3,4,5]
----> 7 thisdict.update(thislist)
TypeError: cannot convert dictionary update sequence element #0 to a sequence
hence we can only update items of an iterable that are in key value pair. So how can a list items be updated in dictionary.
What will happen if i convert a set items in a list using dict() constructor.
In [3]:
thisdict = {'name': 'abhi',
'role': 'trainer',
'course': 'data science'
}
newlist = list(thisdict.items())
print(newlist)
[('name', 'abhi'), ('role', 'trainer'), ('course', 'data science')]
Now , above list is in form of key value pair. if we want to convert list items in a dictionary , our list should have tuples as list items with key value pair in it. For Example:
In [4]:
newlist = [('name', 'abhi'), ('role', 'trainer'), ('course', 'data science')]
newdict = dict(newlist)
print(newdict)
{'name': 'abhi', 'role': 'trainer', 'course': 'data science'}
Remove items from Dictionary :
There are various methods to remove items from dictionary. We will go through each method step by step.
pop() method :
Removes the element with the specified key.
The pop() method removes the specified item from the dictionary.
The value of the removed item is the return value of the pop() method, see example below.
In [8]:
thisdict = {'name': 'abhi',
'role': 'trainer',
'course': 'data science'
}
deleted_value = thisdict.pop('role')
print(thisdict)
print(f'deleted value is {deleted_value}')
{'name': 'abhi', 'course': 'data science'}
deleted value is trainer
popitem() :
The popitem() method removes the item that was last inserted into the dictionary.
The removed item is the return value of the popitem() method, as a tuple, see example below.
In [9]:
thisdict = {'name': 'abhi',
'role': 'trainer',
'course': 'data science'
}
deleted_item = thisdict.popitem()
print(thisdict)
print(f'deleted value is {deleted_item}')
{'name': 'abhi', 'role': 'trainer'}
deleted value is ('course', 'data science')
setdefault :
Returns the value of the specified key. If the key does not exist: insert the key, with the specified value.
Syntax : dictionary.setdefault(keyname, value)
In [11]:
thisdict = {'name': 'abhi',
'role': 'trainer',
'course': 'data science'
}
thisdict.setdefault("role", "not known")
print(thisdict)
{'name': 'abhi', 'role': 'trainer', 'course': 'data science'}
In above code we have set default value of role is 'not known' . So if role key does not exist in dictionary or is removed. default key value pair will be added in dictionary. For Example.
In [12]:
thisdict = {'name': 'abhi',
'course': 'data science'
}
thisdict.setdefault("role", "not known")
print(thisdict)
{'name': 'abhi', 'course': 'data science', 'role': 'not known'}
clear() :
clear method clears all the data in dictionary. for example:
In [13]:
thisdict = {'name': 'abhi',
'role': 'trainer',
'course': 'data science'
}
thisdict.clear()
print(thisdict)
copy() :
copy() method is used to copy contents of a dictionary to another dictioary.For Example:
In [14]:
thisdict = {'name': 'abhi',
'role': 'trainer',
'course': 'data science'
}
thisdict.clear()
print(thisdict)
{'name': 'abhi', 'role': 'trainer', 'course': 'data science'}
dict():
dict() constructor is used to convert a sequence in a dictionary. for Example:
In [7]:
newset = {('name', 'abhi'), ('role', 'trainer'), ('course', 'data science')}
newdict = dict(newset)
print(newdict)
{'name': 'abhi', 'role': 'trainer', 'course': 'data science'}
Assignment:
1.Write a Python script to merge two Python dictionaries 2.Write a Python program to iterate over dictionaries using for loops. 3.Write a Python program to remove a key from a dictionary. 4.Write a Python program to sort a given dictionary by key. 5.Write a Python program to get the maximum and minimum value in a dictionary. 6.Write a Python program to check multiple keys exists in a dictionary.
Last updated