100% found this document useful (1 vote)
360 views31 pages

Class 11 - CS - Dictionary

Python programming

Uploaded by

amogh biyal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
360 views31 pages

Class 11 - CS - Dictionary

Python programming

Uploaded by

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

Python Dictionaries

Dictionaries in Python have a “key”


and a “value of that key”. That is
Python dictionaries are a collection
of some key-value pairs.
Introduction

▪ Dictionary is a collection of elements which is unordered, mutable and


indexed.
▪ Dictionary has keys and values.
▪ Doesn’t have index for values. Keys work as indexes.

▪ Dictionary doesn’t have duplicate member means no duplicate key.

▪ Dictionaries are enclosed by curly braces { }

▪ The key-value pairs are separated by commas ( , )


▪ Values can be assigned and accessed using square brackets [ ].
Syntax:
dictionary-name = {key1:value, key2:value, key3:value, keyn:value}
Empty Dictionary
>>> D = { } #Empty dictionary
>>> D
{}
>>>student =dict()
>>> student
{}

Example:

>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }


>>>marks
{'Maths': 81, 'Chemistry': 78, 'Physics': 75, 'CS': 78}
# there is no guarantee that elements in dictionary can be accessed as per
specific order.
Note: Keys of a dictionary must be of immutable types, such as string,
number, tuple.

Example:
>>> D1={[2,3]:"hello"}
TypeError: unhashable type: 'list'
Characteristics of a Dictionary

1. Unordered Set
A dictionary is an unordered set of key:value pairs .Its values can contain references to any type of
object
2. Not a Sequence
Unlike a string, list, tuple a dictionary is not a sequence because it is unordered set of
elements.The sequences are indexed by a range of ordinal numbers.
3. Indexed by keys , Not Numbers
4. Keys must be unique
5. Mutable:
Like lists, dictionaries are also mutable.We can change the value of a certain key “in place” using
the assignment statement
<dict>[<key>]=<value>
You can even add a new key:value pair to a dictionary using a simple assignment statement. But the
key being added should be unique. If the key already exists, then value is simply changed. 6. Internally
stored as Mappings
Internally, the key:value pairs of a dictionary are associated with one another with some
internal function(called hash-function).This way of linking is called mapping.
Creating a dictionary using dict( ) Constructor:
A. use the dict( ) constructor with single parentheses:
>>> marks=dict(Physics=75,Chemistry=78,Maths=81,CS=78)
>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
B. dict ( ) constructor using parentheses and curly braces: >>>
marks=dict({"Physics":75,"Chemistry":78,"Maths":81, "CS":78})
>>> marks
{
'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}

C. dict( ) constructor using keys and values separately: >>>


marks=dict(zip(("Physics","Chemistry","Maths","CS"),(75,78,81,78)))
>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
zip( ) function clubs first key with first value and so on.
dict( ) constructor using key-value pairs separately:
Example-a
>>> marks=dict([['Physics',75],['Chemistry',78],['Maths',81],['CS',78]]) #
list as argument passed to dict( ) constructor contains list type elements.
>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
Example-b
>>> marks=dict((['Physics',75],['Chemistry',78],['Maths',81],['CS',78])) #
tuple as argument passed to dict( ) constructor contains list type elements
>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
Example-c
>>>marks=dict((('Physics',75),('Chemistry',78),('Maths',81),('CS',78))) #
tuple as argument to dict( ) constructor and contains tuple type elements
>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
ACCESSING ELEMENTS OF A DICTIONARY:

Syntax:
dictionary-name[key]

Example:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81,
"CS":78 } >>> marks["Maths"]
81
>>> marks["English"] #Access a key that doesn’t exist causes an
error KeyError: 'English'

>>> marks.keys( ) #To access all keys in one go


dict_keys(['physics', 'Chemistry', 'Maths', 'CS’])

>>> marks.values( ). # To access all values in one go


dict_values([75, 78, 81, 78])

Lookup : A dictionary operation that takes a key and finds the corresponding value, is
called lookup.
Example to convert the sequence returned by keys() and values()
functions by using list()
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}

>>> list(marks.keys())
['physics', 'Chemistry', 'Maths', 'CS’]

>>> list(marks.values())
[75, 78, 81, 78]
TRAVERSING A DICTIONARY: Syntax:

for <variable-name> in <dictionary-name>:


statement
Example:
>>> for i in marks:
print(i, ": ", marks[i])
OUTPUT:
physics : 75
Chemistry : 78
Maths : 81
CS : 78

CHANGE AND ADD THE VALUE IN A DICTIONARY:


Syntax:
dictionary-name[key]=value
Example:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81,
"CS":78 } >>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
>>> marks['CS']=84 #Changing a value
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
>>> marks['English']=89 # Adding a value
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
DELETE ELEMENTS FROM A DICTIONARY:

There are two methods to delete elements from a dictionary:


(i) using del statement
(ii) using pop( ) method
i) Using del statement:

Syntax:
del dictionary-name[key]

Example:

>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
>>> del marks['English']
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
II. Using pop( ) method:
It deletes the key-value pair and returns the value of deleted element.
Syntax:
dictionary-name.pop( )
Example: >>> marks

{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}


>>> marks.pop('Maths')
81 pop() method allows you to specify what to display when the key
does not exist

>>>marks.pop(‘IP’, ‘Not Found’)


CHECK THE EXISTANCE OF A KEY IN A DICTIONARY:

To check the existence of a key in dictionary, two operators are used: (i) in : it
returns True if the given key is present in the dictionary, otherwise False. (ii) not
in : it returns True if the given key is not present in the dictionary, otherwise
False.

Example:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> 'Chemistry' in marks
True
>>> 'CS' not in marks
False
>>> 78 in marks # in and not in only checks the existence of keys not values False
However, if you need to search for a value in dictionary, then you can use
in operator with the following syntax:
Syntax:
value in dictionary-name. values( )

Example:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> 78 in marks.values( )
True

Nested Dictionary
In Python, a nested dictionary is a dictionary inside a dictionary. It's a
collection of dictionaries into one single dictionary.

nested_dict = { 'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2’}}


people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
print(people)

output:
{1: {'name': 'John', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Marie', 'age': '22', '
'sex': 'Female}}
Access the elements using the [ ]

people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},


2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex’])

Output
John
27
Male
PRETTY PRINTING A DICTIONARY:

To print a dictionary in more readable and presentable form. For pretty


printing a dictionary you need to import json module and then you can
use dumps( ) function from json module.
Example:
>>> print(json.dumps(marks, indent=2))
OUTPUT:
{
"physics": 75,
"Chemistry": 78,
"Maths": 81,
"CS": 78
}

JSON is a syntax for storing and exchanging data.


JSON is text, written with JavaScript object notation.
JSON in Python has a built-in package called json, which can be used to work
with JSON data. Import the json module:

dumps( ) function prints key:value pair in separate lines with the number of
spaces which is the value of indent argument.

import json
d1={"roll":2,"Name":"Riya","English":45,"Csc":49,'phy':34,'che':55,'bio':66
} print(json.dumps(d1,indent=2))
print(d1)
DICTIONARY FUNCTIONS:
Consider a dictionary marks as follows:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
• fromkeys()

• The fromkeys() method creates a new dictionary from the given sequence of elements with a
value provided by the user.

• The syntax of fromkeys() method is:

dictionary.fromkeys(sequence[, value])

fromkeys() Parameters

fromkeys() method takes two parameters:


sequence - sequence of elements which is to be used as keys for the new dictionary

value (Optional) - value which is set to each each element of the dictionary

fromkeys() method returns a new dictionary with the given sequence of elements as the keys of the
dictionary.
# vowels keys vowels = dict.fromkeys(keys)
keys = {'a', 'e', 'i', 'o', 'u' } print(vowels)
OUTPUT vowels = dict.fromkeys(keys, value)
{'a': None, 'u': None, 'o': None, 'e': print(vowels)
None, 'i': None}
# vowels keys OUTPUT
keys = {'a', 'e', 'i', 'o', 'u' }
value = 'vowel' {'a': 'vowel', 'u': 'vowel', 'o': 'vowel', 'e':
'vowel', 'i': 'vowel'}
#Example1

d1=dict.fromkeys([2,4,6,8],100)
print(d1)
d2=dict.fromkeys([12,14,16,18])
print(d2)
Your school has decided to deposit scholarship amount of 2500 to some selected students.
Write a program to input the selected student's roll num
and create a dictionary for the same.'''
'''l1=[]
n=int(input("How many students:")) #2
for a in range(n): #2,a=0,a=1
r=int(input("Enter Rollno:"))#12 20
l1.append(r) #[12,20]
s=dict.fromkeys(l1,2500)
print("Created dictionary")
print(s)
Making a shallow copy using copy() method
• Creating copy using assignment operator
Creating copy using copy()
copy() method returns a shallow copy of the dictionary. It doesn't modify the original
dictionary.

The syntax of copy() is:


dict.copy()
copy() Parameters
copy() method doesn't take any parameters.

original = {1:'one', 2:'two'}


new = original.copy()
print('Orignal: ', original)
print('New: ', new)
clear()
The clear() method removes all items from the dictionary.
The syntax of clear() is:
dict.clear()

pop()
The pop() method removes the specified item from the
dictionary. • Syntax
dictionary.pop(keyname, defaultvalue)

popitem()
The popitem() method removes the item that was last inserted into the dictionary. In
versions before 3.7, the popitem() method removes a random item. The removed
item is the return value of the popitem() method, as a tuple
#deleting elements-
clear(),del,pop(),popitems()
stu={1:'Neha',2:'Sona',3:'Sohan',4:'Preeti'}
stu.pop(2)
stu.pop(6)
print(stu)
stu.popitem() #delete last entered item.LIFO
order stu.clear()
print(stu)
Sorted() – return the sorted list of dictionary keys

s={'roll':3,'name':"riya",'Csc':60,'English':58
} d=sorted(s)
d1=sorted(s,reverse=True)
d2=sorted(s.keys())
d3=sorted(s.values())
print(d)
print(d1)
print(d2)
print(d3)
d4=sorted(s.items())
print(d4)
max(),min(),sum()

min() - To find the key with minimum value in the dictionary .


max() - To find the key with maximum value in the
dictionary . sum() - Add all the values of a dictionary together
to find the sum.
#min,max,sum (homegenius type:same type)

s={2:32,4:45,5:60,6:58}
print(min(s))
mi=min(s.values())
print(mi)
print("\nmaximum")
print(max(s))
ma=max(s.values())
print(ma)
print("\nsum")
print(sum(s))
su=sum(s.values())
print(su)
THANK YOU

You might also like