DICTIONARY
DICTIONARY
Dictionary is a mutable unordered set of key & value pair. It is a container that
contains data, enclosed within curly braces. The pair i.e., key & value is known as
item. The key passed in the item must be unique. The key & the value is separated
by a colon (:). This pair is known as item. Items are separated from each other by a
comma (,). Different items are enclosed within a curly brace & this forms Dictionary.
They are also known as associative arrays or mappings or hashes.
Creating a dictionary
To create a dictionary, we need to include key: value pairs in curly braces.
Syntax:- <dictionary_name> = { <key> : <value>, <key> : <value>, <key> : <value>,
_____}
Subjects = {“X” : “SOCIAL SCIENCE”, “XI” : “COMPUTER SCIENCE”, “XII” :
“PHYSICS”}
DICT1 = { } empty dictionary
Note:- Keys of the dictionary must be of immutable types, such as string, number,
tuple (containing only immutable entries).
Dictionary is mutable i.e.; values can be updated.
Key must be unique & immutable. Value is accessed by key. Value can be updated
while key cannot be changed.
Dictionary is known as Associative array since the Key works as Index & they are
decided by the user.
Accessing Values
Since Index is not defined, a Dictionaries value can be accessed by their keys.
data1 = {'Id' : 100, 'Name' : 'Suresh', 'Profession' : 'Developer'}
data2 = {'Id' : 101, 'Name' : 'Ramesh', 'Profession' : 'Trainer'}
print (“Id of 1st employer is”, data1['Id'])
print (“Id of 2nd employer is”, data2['Id'])
print (“Name of 1st employer:”, data1['Name'])
print (“Profession of 2nd employer:”, data2['Profession'])
Output:- Id of 1st employer is 100
Id of 2nd employer is 101
Name of 1st employer is Suresh
Profession of 2nd employer: Trainer
Traversing a dictionary
Traversing a sequence means accessing & processing each element. It is done by
loops.
data1 = {'Id' : 100, 'Name' : 'Suresh', 'Profession' : 'Developer'}
for a in data1:
print(a, “:”, data1[a])
Output:- Id : 100
Name : Suresh
Profession : Developer
1
Accessing keys & values simultaneously
To see or access all keys in a dictionary we use <dictionary>.keys( ) method & to see
or access all values in a dictionary we use <dictionary>.values( ) method.
data1 = {'Id' : 100, 'Name' : 'Suresh', 'Profession' : 'Developer'}
print(data1.keys( ))
print(data1.values( ))
Output:- dict_keys(['Id', 'Name', 'Profession'])
dict_values([100, 'Suresh', 'Developer'])
Properties of dictionary
➢ unordered set
It is an unordered set of key : value pairs. Its values contain references to any
type of object.
➢ not a sequence
Unlike like string list or tuple, dictionary is not a sequence rather it is an
unordered set of elements.
➢ indexed by keys not numbers
Dictionaries are indexed by keys & keys can be any immutable type, such as
string, number, tuple (containing only immutable entries).
➢ keys must be unique
Keys within a dictionary must be unique, since keys are used to identify values
in a dictionary, there cannot be duplicate keys in a dictionary.
➢ Mutable
We can change the value of certain key using assignment statement.
<dictionary>[<key>] = <value>
data1 = {'Id' : 100, 'Name' : 'Suresh', 'Profession' : 'Developer'}
print(data1)
data1['Id'] = 107
print(data1)
Output:- {'Id': 100, 'Name': 'Suresh', 'Profession': 'Developer'}
{'Id': 107, 'Name': 'Suresh', 'Profession': 'Developer'}
➢ internally stored as mapping
2
Multiple ways to create dictionaries
initializing a dictionary
In this method, all key:value pairs of a dictionary are written collectively, separated
by commas & enclosed in curly braces.
data1 = {'Id' : 100, 'Name' : 'Suresh', 'Profession' : 'Developer'}
adding key:value pairs to an empty dictionary
In this method first an empty dictionary is created, then keys & values are added to
it one pair at a time.
We can create an empty dictionary by two ways:
➢ By giving dictionary contents in empty curly braces.
Employees = { }
➢ By using dictionary constructor method dict( )
Employees = dict( )
Now we add key : value pairs one at a time
<dictionary>[<key>] = <value>
Employees = { }
Employees['name'] = “amit”
Employees['age'] = 26
print(Employees) {'name': 'amit', 'age': 26}
3
Updating elements to dictionary
We can update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry.
data1 = {'Id' : 100, 'Name' : 'Suresh', 'Profession' : 'Developer'}
data2 = {'Id' : 101, 'Name' : 'Ramesh', 'Profession' : 'Trainer'}
data1['Profession'] = 'Manager'
data2['Salary'] = 20000
data1['Salary'] = 15000
print (data1)
print (data2)
Output:- {'Id' : 100, 'Name' : 'Suresh', 'Profession' : 'Manager', 'Salary' : 15000}
{'Id' : 101, 'Name' : 'Ramesh', 'Profession' : 'Trainer', 'Salary' : 20000}
Nested dictionaries
Adding dictionaries as values inside a dictionary is termed as nested dictionaries.
A dictionary contains details of two workers with their names as keys & other details
in the form of dictionary as value. WAP to print the workers details in record format.
Employees = {'AMIT':{'AGE':26, 'SALARY':40000}, 'RAJ':{'AGE':28, 'SALARY': 45000}}
for key in Employees :
print (“Employee”, key, “:”)
print('Age:', str(Employees[key]['AGE']))
print('Salary:', str(Employees[key]['SALARY']))
Output:- Employee AMIT:
Age: 26
Salary: 40000
Employee RAJ:
Age: 28
Salary: 45000
4
Checking the existing of the key
Using membership operators, we can check the existence of a key in dictionary.
Syntax:- <key> in <dictionary>
<key> not in <dictionary>
The in operator will return True if the given key is present in the dictionary,
otherwise False.
The not in operator will return True if the given key is not present in the dictionary,
otherwise False.
Dictionary methods
➢ len( )
This method is used to returns the length of dictionary i.e., count the elements
in dictionary.
Syntax:- len(<dictionary>)
It takes dictionary as arguments & returns an integer.
data1 = {'Id' : 100, 'Name' : 'Suresh', 'Profession' : 'Developer'}
print(len(data1)) 3
5
➢ clear( )
It is used to removes all the items from the dictionary & dictionary becomes
empty.
Syntax:- dictionary.clear( )
data1 = {'Id' : 100, 'Name' : 'Suresh', 'Profession' : 'Developer'}
data1.clear( )
print(data1) {}
➢ keys( )
This method returns all the keys in the dictionary as a sequence of keys.
Syntax:- <dictionary>.keys( )
dict = {'sun' : ”Sunday”, 'mon' : ”Monday”, 'tues' : 'Tuesday'}
print(dict.keys( )) dict_keys(['sun', 'mon', 'tues'])
➢ values( )
This method returns all the values in the dictionary as a sequence. It can be in
no particular order.
Syntax:- <dictionary>.values( )
dict = {'sun' : ”Sunday”, 'mon' : ”Monday”, 'tues' : 'Tuesday'}
print(dict.values( )) dict_values(['Sunday', 'Monday', 'Tuesday'])
➢ get( )
This method we can get the item with the given key. If the given item is not
present, it gives error.
Syntax:- dictionary.get(key,[default])
It takes key as essential argument & returns the corresponding value if the key
exists. If the key doesnot exists it gives the default argument as message
otherwise it will give error.
data1 = {'Id' : 100, 'Name' : 'Suresh', 'Profession' : 'Developer'}
print(data1.get('Name')) Suresh
print(data1.get('Address', “Error!! Not found”)) Error!! Not found
print(data1.get('Desig')) None
➢ items( )
This method is used to return all the items in the dictionary as a sequence of
tuple.
Note:- It can be in no particular order.
Syntax:- <dictionary>.items( )
It takes no arguments & returns a sequence of pairs.
data1 = {'Id' : 100, 'Name' : 'Suresh', 'Profession' : 'Developer'}
list1 = data1.items( )
for x in list1 :
print(x)
Output:- ('Id', 100)
('Name', 'Suresh')
('Profession', 'Developer')
6
➢ update( )
This method merges key : value pairs from the new dictionary into the original
dictionary, adding or replacing as needed.
Syntax:- <dictionary>.update(<other-dictionary>)
data1 = {'Id' : 100, 'Name' : 'Suresh', 'Profession' : 'Developer'}
data2 = {'Id' : 101, 'Name' : 'Akash', 'Profession' : 'Programmer'}
data1.update(data2)
print(data1)
Output:- {'Id': 101, 'Name': 'Akash', 'Profession': 'Programmer'}
Note:- the elements of data2 have overridden the elements of data1
➢ fromkeys( )
This function is used to create dictionary from a collection of keys(tuple/list).
Syntax:- dict.fromkeys(<collection of keys>, <default values to be assigned>)
The values passed to this function is a default value for all the defined indexes,
else None is assigned to all the items.
keys1 = [1,2,3,4]
values1 = 100
D1 = dict.fromkeys(keys1, values1)
print(D1)
Output:- {1: 100, 2: 100, 3: 100, 4: 100}
➢ copy( )
We cannot copy a dictionary using assignment (‘=’) operator as it will create a
reference to same dictionary variable. For copying contents of dictionary into
another dictionary we use copy( ) method.
Syntax:- <dictionary>.copy( )
D1 = {'Name' : 'Akash','DOB' : '2002-03-11','Marks' : '98'}
D2 = D1.copy( )
print(“D2 :”, D2)
print(“Location of D1:”, id(D1))
print(“Location of D2:”, id(D2))
Output:- D2 : {'Name' : 'Akash', 'DOB' : '2002-03-11', 'Marks' : '98'}
Location of D1: 1620563506624
Location of D2: 1620563506688
➢ pop( )
This method removes and returns the dictionary element associated to passed
key.
Syntax:- dict.pop(key, <msg>)
If the key is found, it is deleted and its value is returned, otherwise Python will
raise and error. In case message is given then the message will be displayed if
the given key is not found in the dictionary.
D1 = {'Name' : 'Akash','DOB' : '2002-03-11','Marks' : '98'}
print(D1)
print(D1.pop('Salary', "Not Found"))
print(D1.pop( ))
print(D1.pop('Name'))
7
Output:- {'Name': 'Akash', 'DOB': '2002-03-11', 'Marks': '98'}
Not Found
Error
Akash
➢ popitem( )
This method removes last item from dictionary & returns this deleted item.
Syntax:- D.popitem( )
D1 = {'Name' : 'Akash','DOB' : '2002-03-11','Marks' : '98'}
print(D1)
S = D1.popitem( )
print(“Removed Item:”, S)
Output:- D2 : {'Name': 'Akash', 'DOB': '2002-03-11', 'Marks': '98'}
Removed Item: ('Marks', '98')
➢ max( ) & min( )
The method max( ) returns key having maximum value & min( ) returns the
key having minimum value.
D1 = {'STUDENT1' : '46', 'STUDENT2' : '48', 'STUDENT3' : '41'}
print(“Highest Key with its value:”, max(D1.items()))
print(“Lowest Key with its value:”, min(D1.items()))
print(“Highest Key:”, max(D1))
print(“Lowest Key:”, min(D1))
print(“Highest Value:”, max(D1.values()))
print(“Lowest Value:”, min(D1.values()))
Output:- Highest Key with its value: ('STUDENT3', '41')
Lowest Key with its value: ('STUDENT1', '46')
Highest Key: STUDENT3
Lowest Key: STUDENT1
Highest Value: 48
Lowest Value: 41
➢ sorted( )
This method sorts the elements of a dictionary by its key or value. It doesnot
change the original dictionary.
D1 = {'STUDENT1' : '46', 'STUDENT2' : '48', 'STUDENT3' : '41'}
L1 = sorted(D1)
print(L1)
L2 = dict(sorted(D1.items()))
print(L2)
L3 = sorted(D1.values())
print(L3)
Output:- ['STUDENT1', 'STUDENT2', 'STUDENT3']
{'STUDENT1': '46', 'STUDENT2': '48', 'STUDENT3': '41'}
['41', '46', '48']
8
➢ setdefault( )
This method returns the item with the specified key. If the key does not exist, it
inserts the key with the specified value.
Syntax:- <value>=<Dict>.setdefault(<keys>,<default_value>)
The setvalue( ) method returns value of the key, if it is in the dictionary
None, if key is not in the dictionary & default value is not specified.
Default value, if key is not in the dictionary & default value is specified.
D1 = {'Name' : 'Akash', 'Gender' : 'Male'}
print(D1)
D1_Name = D1.setdefault('Name','Name not available')
D1_DOB = D1.setdefault('DOB','Date not available')
D1_Gender = D1.setdefault('Gender')
D1_Mobile = D1.setdefault('Mobile')
print(“Name :”, D1_Name)
print(“DOB :”, D1_DOB)
print(“Gender :”, D1_Gender)
print(“Mobile :”, D1_Mobile)
Output:- {'Name': 'Akash', 'Gender': 'Male'}
Name : Akash
DOB : Date not available
Gender : Male
Mobile : None