Thursday , November 21 2024
Class XI & XII Computer Science: Python

Dictionary in Python: 11th Class Computer Science Chapter 09

Chapter Name: Dictionary in Python [Chapter 08]
Class: 11th
Subject: Computer Science

9.1 Introduction: Dictionary in Python

Definition – Dictionary in Python:

  • Dictionary in Python 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: Dictionary in Python

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.

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}

Note: 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}

In this case the keys and values are enclosed separately in parentheses and are given as argument to the zip( ) function. zip( ) function clubs first key with first value and so on.

D) 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}

9.3 Accessing Elements of  a Dictionary: Dictionary in Python

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 <variable-name> in <dictionary-name>:
statement

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
>>> mark
{‘physics’: 75, ‘Chemistry’: 78, ‘Maths’: 81, ‘CS’: 84, ‘English’: 89}

9.6 Delete Elements From a Dictionary:

There are two methods to delete elements from a dictionary:

  • using del statement
  • using pop( ) method

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}

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

9.7 Check the Existence of Key in a Dictionary: Dictionary in Python

To check the existence of a key in dictionary, two operators are used:

in : it returns True if the given key is present in the dictionary, otherwise False.
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 in 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
}

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.

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 }

Check Also

Class XI & XII Computer Science: Python

List in Python: 11th Class Computer Science Chapter 07

Chapter Name: List in Python [Chapter 07] Class: 11th Subject: Computer Science 7.1 Introduction: List …