DICTIONARY IN PYTHON
Computer Science
Class -XI
Code No. 083
2023-24
CLASS-XI
SUBJECT: COMPUTER SCIENCE (083) – PYTHON
INDEX
NO. CHAPTER NAME
1 INTRODUCTION TO PYTHON
2 PYTHON FUNDAMENTALS
3 DATA HANDLING
4 FLOW OF CONTROL
5 FUNCTIONS IN PYTHON
6 STRING IN PYTHON
7 LIST IN PYTHON
8 TUPLE IN PYTHON
9 DICTIONARY IN PYTHON
|
CHAPTER-9
DICTIONARY IN PYTHON
9.1 INTRODUCTION:
Dictionary is a collection of elements which
is unordered, changeable 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 ( , )
A dictionary key can be almost any Python type,
but are usually numbers or strings.
Values can be assigned and accessed using
square brackets [ ].
9.2 CREATING A DICTIONARY:
Syntax:
dictionary-name = {key1:value, key2:value,
key3:value, keyn:value}
Example:
>>> marks = { "physics" : 75, "Chemistry" :
78, "Maths" : 81, "CS":78 }
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths':
81, 'CS': 78}
>>> D = { } #Empty dictionary
>>> D
{ }
>>> marks = { "physics" : 75, "Chemistry" :
78, "Maths" : 81, "CS":78 }
{'Maths': 81, 'Chemistry': 78, 'Physics':
75, 'CS': 78} # there is no guarantee that
# elements in dictionary can be accessed
as per specific order.
ApnaJila ApnaJila 86
Note: Keys of a dictionary must be of immutable
types, such as string, number, tuple.
Example:
>>> D1={[2,3]:"hello"}
TypeError: unhashable type: 'list'
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}
In the above case the keys are not enclosed
in quotes and equal sign is used
for assignment rather than colon.
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}
ApnaJila ApnaJila 88
9.3 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.
9.4 TRAVERSING A DICTIONARY:
Syntax:
for in :
statement
ApnaJila ApnaJila 89
Example:
>>> for i in marks:
print(i, ": ", marks[i])
OUTPUT:
physics : 75
Chemistry : 78
Maths : 81
CS : 78
9.5 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}
ApnaJila ApnaJila 90
9.6 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
ApnaJila ApnaJila 91
9.7 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
9.8 PRETTY PRINTING A DICTIONARY:
What is Pretty Printing?
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
}
dumps( ) function prints key:value pair in separate
lines with the number of spaces
which is the value of indent argument.
9.9 COUNTING FREQUENCY OF ELEMENTS IN A LIST
USING DICTIONARY
Steps:
1. import the json module for pretty printing
2. Take a string from user
3. Create a list using split( ) function
4. Create an empty dictionary to hold words and frequency
5. Now make the word as a key one by one from the list
6. If the key not present in the dictionary then
add the key in dictionary and count
7. Print the dictionary with frequency of elements
using dumps( ) function.
ApnaJila ApnaJila 93
Program:
import json
sentence=input("Enter a string: ")
L = sentence.split()
d={ }
for word in L:
key=word
if key not in d:
count=L.count(key)
d[key]=count
print("The frequqency of elements in the list is as follows: ")
print(json.dumps(d,indent=2))
9.10 DICTIONARY FUNCTIONS:
Consider a dictionary marks as follows:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths"
: 81, "CS":78 }
S.
No.
Function
Name Description Example
1 len( ) Find the length of a
dictionary.
Syntax:
len (dictionary-name)
>>> len(marks)
4
2 clear( ) removes all elements
from the dictionary
Syntax:
dictionary-name.clear( )
>>> marks.clear( )
>>> marks
{ }
ApnaJila ApnaJila 94
3. get( ) Returns value of a key.
Syntax:
dictionary-name.get(key)
>>> marks.get("physics")
75
Note: When key does not exist it returns no value
without any error.
>>> marks.get('Hindi')
>>>
4 items( ) returns all elements as a
sequence of (key,value)
tuples in any order.
Syntax:
dictionary-name.items( )
>>> marks.items()
dict_items([('physics', 75), ('Chemistry',
78), ('Maths', 81), ('CS', 78)])
Note: You can write a loop having two variables
to access key: value pairs.
>>> seq=marks.items()
>>> for i, j in seq:
print(j, i)
OUTPUT:
75 physics
78 Chemistry
81 Maths
78 CS
5 keys( ) Returns all keys in the
form of a list.
Syntax:
dictionary-name.keys( )
>>> marks.keys()
dict_keys (['physics', 'Chemistry',
'Maths', 'CS'])
6 values( ) Returns all values in the
form of a list.
Syntax:
dictionary-name.values( )
>>> marks.values()
dict_values([75, 78, 81, 78])
7 update( ) Merges two dictionaries.
Already present elements
are override.
Syntax:
dictionary1.update(dictionary2)
Example:
>>> marks1 = { "physics" : 75, "Chemistry" :
78, "Maths" : 81, "CS":78 }
>>> marks2 = { "Hindi" : 80, "Chemistry" :
88, "English" : 92 }
>>> marks1.update(marks2)
>>> marks1
{'physics': 75, 'Chemistry': 88, 'Maths': 81,
'CS': 78, 'Hindi': 80, 'English': 92}
ApnaJila ApnaJila 95
|
|