0% found this document useful (0 votes)
4 views6 pages

Dictionaries

A dictionary is an unordered collection of key-value pairs, where keys are immutable types and values are mutable. Dictionaries can be created in various ways, accessed using square brackets, and modified by adding or updating elements. Python provides built-in functions and methods for manipulating dictionaries, including adding, deleting, and retrieving items.

Uploaded by

Harish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views6 pages

Dictionaries

A dictionary is an unordered collection of key-value pairs, where keys are immutable types and values are mutable. Dictionaries can be created in various ways, accessed using square brackets, and modified by adding or updating elements. Python provides built-in functions and methods for manipulating dictionaries, including adding, deleting, and retrieving items.

Uploaded by

Harish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Dictionaries

A dictionary is an unordered sequence of key-value pairs.


 Key and value in a key-value pair in a dictionary are separated by a colon. Further, the key : value
 pairs in a dictionary are separated by commas and are enclosed between curly parentheses.
 The keys of the dictionaries are immutable types such as Integers or Strings etc.
 Indices in a dictionary can be of any immutable type and are called keys.
 Dictionaries are mutable.

Creating Dictionaries
A Dictionary can be created in three different ways:
Empty Dictionary
>>>D = { } # Empty Dictionary
Dictionary using literal notation
>>>D = {“Name” : “Mohan”, “Class” : “XI”, “City” : “Gurdaspur”}
>>>print(D)
{“Name” : “Mohan”, “Class” : “XI”, “City” : “Gurdaspur”}
>>>print(D[“City”])
“Gurdaspur”
Dictionary using dict() function
Dict() function is used to create a new dictionary with no items. For example,
>>> Months = dict() # Creates an empty dictionary
>>>print(Month) # Prints an empty dictionary
We can use Square Brackets( [ ] with keys for accessing and initializing dictionary values. For Example:
>>> Months[0] = ‘January’
>>> Months[1] = ‘February’
>>>Months[2] = ‘March’
>>> print(Months)
{0 : ’January’, 1: ’February’ , 2 : ’March’}

>>> Months = dict(Jan = 31, Feb = 28, March = 31) # Creating dictionary by giving values in dict()
function
>>> print(Months)
{‘Jan’ : 31, ‘Feb’ : 28, ‘March’ : 31}

Accessing Elements of a Dictionary


Elements of Dictionary may be accessed by writing the Dictionary name and key within square
brackets ([ ] ) as given below:
>>> D = {0 : “Sunday”, 1 : “Monday”, 2: “Tuesday”}
>>> print(D[1])
Monday
Traversing a Dictionary
Dictionary items can be accessed using a for loop.
for x in D:
print(D [x])
Output
Sunday
Monday
T uesday

Mutability of Dictionary
Dictionary like lists are mutable, it means dictionary can be changed, new items can be added and
existing items can be updated.

Adding an Element in Dictionary


We can add new element (key : value pair) to a dictionary using assignment, but the key being added
must not exist in dictionary and must be unique.
>>> D[4] = “Wednesday” # if a new key is given, new item is added
>>> print(D)
{0 : “Sunday”, 1 : “Monday”, 2: “Tuesday”, 3: “Wednesday”}

Updating / Modifying an element in Dictionary


We can change the individual element of dictionary as given below:
>>> D[1] = “Mon” # Value of Key (1) is changed
>>> print(D)
{0 : “Sunday”, 1 : “Mon”, 2: “Tuesday”, 3: “Wednesday”}
Dictionary Functions and Methods
Built –in functions and methods are provided by Python to manipulate Python dictionaries.
len() function:
It is used to find the length of the dictionary, i.e., the count of the key : value pair.
Exp. D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
length = len(D)
print("Length of Dictionary : ", length)
Output
Length of Dictionary : 4

dict() function:
The dict() function creates a dictionary.
Accessing Items, Keys and Values – get(), items(), keys(), values () methods
get( ) Method : it returns value of the given key
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> value = D.get('Rama', 'Key not Found')
>>> print("Age of Rama is : ", value)

>>> value = D.get('Mohit', 'Key not Found') # if key is not in the dictionary, it shows key not found
>>> print("Age of Mohit is : ", value)

Output
Age of Rama is : 22
Age of Mohit is : Key not Found

items( ) Method :
It returns all items of a dictionary in the form of list of tuple of (key:value)
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> print(D.items())

Output
dict_items([('Ram', 20), ('Mohan', 30), ('Rama', 22), ('Rashi', 32)])

keys( ) Method :
It returns list of all the keys of the dictionary.
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> print(D.keys())

Output
dict_keys(['Ram', 'Mohan', 'Rama', 'Rashi'])

values( ) Method :
It returns list of all the values of the dictionary.
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> print(D.values())
Output
dict_values([20, 30, 22, 32])

update( ) Method :
This function merges key : value pairs from the new dictionary into the original dictionary, adding or
replacing
as needed. The items in the new dictionary are added to the old one and override any items already there with
the same keys.
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> D2 = {'A' : 20, 'Mohan' : 60, 'Rama' : 62, 'B' : 32}
>>> D.update(D2)
>>> print("D => ",D)
>>> print("D2 => ", D2)

Output
D => {'Ram': 20, 'Mohan': 60, 'Rama': 62, 'Rashi': 32, 'A': 20, 'B': 32}
D2 => {'A': 20, 'Mohan': 60, 'Rama': 62, 'B': 32}

Deleting elements from dictionary:


del statement
del statement is used to delete a dictionary element or dictionary entry, i.e., a key:value pair.
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> print(D)
>>> del D["Mohan"] # to delete a key from the dictionary i.e. “Mohan”
>>> print(D)
>>> del D # To delete the whole dictionary
Output

{'Ram': 20, 'Mohan': 30, 'Rama': 22, 'Rashi': 32} # Complete Dictionary
{'Ram': 20, 'Rama': 22, 'Rashi': 32} # After deleting “Mohan”

clear ( ) method
It empties the dictionary.
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> print(D)
>>> D.clear()
>>> print("Dictionary after Clear : ", D)

Output
{'Ram': 20, 'Mohan': 30, 'Rama': 22, 'Rashi': 32}
Dictionary after Clear : {}

pop ( ) method
It removes and returns the dictionary element associated to passed key.
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> print("Removed Item : ", D.pop("Rama"))

Output
Removed Item : 22

popitem ( ) method
It removes and returns the last dictionary element.
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> print("Removed Item : ", D.popitem())

Output
Removed Item : ('Rashi', 32)

sorted ( ) method
It returns a sorted list of the dictionary keys. It is used as below:
>>> D = {'Ram' : 20, 'Mohan' : 30, 'Rama' : 22, 'Rashi' : 32}
>>> print(sorted(D)) # sort the keys in ascending order
>>> print(sorted(D), reverse = False) # sort the keys in ascending order
>>> print(sorted(D), reverse = True) # sort the keys in descending order

Output
['Mohan', 'Ram', 'Rama', 'Rashi']
['Mohan', 'Ram', 'Rama', 'Rashi']
['Rashi', 'Rama', 'Ram', 'Mohan']

max ( ) , min() and sum() Functions


These functions work with the keys of a dictionary. Dictionaries must be homogeneous to use the
functions.
 max() function gives the maximum value
 min() function gives the minimum value
 sum() function gives the sum of keys
>>> D = {1: "Monday", 2: "Tuesday", 3:"Wednesday"}
>>> print("Max = ",max(D))
>>> print("min = ",min(D))
>>> print("Sum = ", sum(D))

Output
Max = 3
min = 1
Sum = 6

fromkeys ( ) method
This method is used to create a new dictionary from a sequence containing all the keys and common
value, which will be assigned to all the keys. Keys argument must be an interable sequence (First argument).
When value not given, it will take None as the values for the keys (Second Argument)
Exp.
>>> D = dict.fromkeys([2,4,5,8],200) # When Value given
>>> print(D)
>>> D = dict.fromkeys([2,4,5,8]) # When value not given, it will take None as the values for the keys
print(D)

Output
{2: 200, 4: 200, 5: 200, 8: 200}
{2: None, 4: None, 5: None, 8: None}

setdefault ( ) method
This method inserts a new key: value pair only if the key does not exist. If the key already exists, it
returns the current value of the key.
Exp.
>>> D = {1: "Monday", 2: "Tuesday", 3:"Wednesday"}
>>> D.setdefault(2,"Tuesday") # Key already exists, it will not insert
>>> print(D)
>>> D.setdefault(4,"Thursday") # New Key, it will be inserted
>>> print(D)

Output
{1: 'Monday', 2: 'Tuesday', 3: 'Wednesday'}
{1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday'}

You might also like