1 of 34

NAVODAYA VIDYALAYA SAMITI� HYDERABAD REGION

E-CONTENT

​

COMPUTER SCIENCE CLASS XI

2 of 34

COMPUTATIONAL THINKING AND PROGRAMMING-1

DICTIONARY IN PYTHON

SHIFA JAMES

PGT CS , JNV KADAPA

3 of 34

CONTENTS

  • Definition, Creation, Accessing elements of a dictionary
  • Add an item, modify an item in a dictionary; Traversal
  • Functions/methods – len(), dict(), keys(), values(), items(), get(), update(), del(), del, clear(), fromkeys(), copy(), pop(), popitem(), setdefault(), max(), min(), count(), sorted() , copy();
  • Suggested programs :
    • count the number of times a character appears in a given string using a dictionary,
    • create a dictionary with names of employees, their salary and access them.

4 of 34

Learning Objectives

After completing this lesson, the students should be able to:

​

  • Understand the need of a Dictionary
  • Understand how to implement it in python.
  • Gain knowledge about Different types Operations in Dictionary
  • Understand about Different Methods and Built-in Functions in Dictionary
  • Implementing Dictionary in Program

5 of 34

INTRODUCTION

  • Have you used a Telephone Directory ?
  • How are the contents arranged in a Telephone Directory ?
  • Subscribers number gets stored according to his name and address.
  • Here name becomes a key and phone number becomes a value.
  • In dictionary, we have a concept of Key – Value pair.

​

6 of 34

Dictionary - Definition

A Dictionary is an unordered collection of items where each item is a key-value pair.

It is a mapping between a set of keys and a set of values. The key-value pair is called an item.

Elements of a Dictionary are enclosed in curly brackets { } and are separated by commas.

Dictionaries are mutable data types in the form of key:value , where key is used to access the corresponding Value .

Keys are unique within a dictionary and are of immutable data types whereas Values are of mutable types

7 of 34

Internally stored as Mappings

​

Internally, the key:value pair are associated with one another with some internal function(called hash function). This way of linking is called as mapping

8 of 34

Creating a Dictionary

  • To create a dictionary, it is needed to collect pairs of key:value in “{ }”.
    • <dictionary-name> = { <key1>:<value1>, <key2>:<value2>, <key3>:<value3>. . . }

​

    • Example:

Teachers = {“Rajeev”:”Math”, “Amal”:”Physics”, ”Arun”:”Chemistry“ , “ SJ”:”CS” }

​

In above given example :

Key-value pair

Key

Value

“Rajeev”:”Math”

“Rajeev”

“Math”

“Amal”:”Physics”

“Amal”

“Physics”

“Arun”:”Chemistry”

“Arun”

“Chemistry”

“SJ”:”CS”

“SJ”

“CS”

9 of 34

Different methods of creating a Dictionary

1) dict1 is an empty Dictionary created . Curly braces are used for empty dictionary

Example :

>>> dict1 = {}

>>> dict1

{}

  1. dict2 is an empty dictionary created using built-in function

>>> dict2 = dict()

>>> dict2

{}

10 of 34

Different methods of creating a Dictionary

3) dict3 is the dictionary that maps names of the students to respective marks in percentage

>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}

>>> dict3

{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}

​

11 of 34

Accessing keys and values simultaneously

  • To access only keys of a dicionary , we can use the function keys()
  • >>> mydict={'empno':1,'name':‘Arjun','dept':'sales','salary':20000}
  • >>>mydict.keys()
  • dict_keys(['empno', 'name', 'dept', 'salary'])
  • To access only values of a dicionary , we can use the function values()
  • >>>mydict.values()
  • dict_values([1, ‘Arjun', 'sales', 20000])
  • We can convert the sequence returned by keys() and values() by using list() as shown below:
  • >>> list(mydict.keys())
  • ['empno', 'name', 'dept', 'salary']
  • >>> list(mydict.values()) [1, ‘Arjun', 'sales', 20000]

​

12 of 34

Characteristics of a Dictionary

  • Unordered set
    • A dictionary is a unordered set of key:value pair
  • Not a sequence
    • Unlike a string, tuple, and list, a dictionary is not a sequence because it is unordered set of elements. The sequences are indexed by a range of ordinal numbers. Hence they are ordered but a dictionary is an unordered collection
  • Indexed by Keys, Not Numbers
    • Dictionaries are indexed by keys. Keys are immutable type

​

13 of 34

Characteristics of a Dictionary

  • Keys must be unique
    • Each key within dictionary must be unique. However two unique keys can have same values.

​

For example

Data = {1:100, 2:200,3:300,4:200}

  • Mutable
    • Like lists, dictionary are also mutable. We can change the value of a certain “key” in place
  • Data[3]=400

So, to change value of dictionary the format is :

DictionaryName[“key” / key ]=new_value

You can even add new key:value pair using the same format:

DictionaryName[“key” / key ]=new_value

14 of 34

Accessing Elements in a Dictionary

  • The items of a dictionary are accessed via the keys rather than via their relative positions or indices. Each key serves as the index and maps to a value.

For example :

>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}

>>> dict3['Ram']

89

>>> dict3['Sangeeta']

85

>>> dict3['Shyam'] #the key does not exist

KeyError: 'Shyam'

15 of 34

DICTIONARIES ARE MUTABLE

Add new item, Update an item , Delete an item

16 of 34

Adding elements to Dictionary

We can add a new item to the dictionary as shown in the following example:

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}

>>> dict1['Meena'] = 78

>>> dict1

{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85, 'Meena': 78}

​

Note : The new item added will be at the end of the dictionary

17 of 34

Updating elements in Dictionary

  • The existing dictionary can be modified by just overwriting the key-value pair. Example to modify a given item in the dictionary:

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}

#Marks of Suhel changed to 93.5

>>> dict1['Suhel'] = 93.5

>>> dict1

{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5, 'Sangeeta': 85}

18 of 34

Deleting elements from Dictionary

Method 1 - Using del command

  • Syntax :

del dictionaryName[“Key”]

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}

>>> del dict1[‘Ram’]

>>> dict1

{'Mohan':95, 'Suhel':92, 'Sangeeta':85}

Note :

If you try to remove the item whose key does not exists, the python runtime error occurs.

​

19 of 34

Deleting elements from Dictionary

Method 2 - Using pop() function

Syntax :

dictionaryName.pop([“Key”])

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}

>>> dict1.pop(‘Suhel’)

>>>dict1

{'Mohan':95,'Ram':89, 'Sangeeta':85}

Note:

if key passed to pop() doesn’t exists then python will raise an exception.

​

20 of 34

Traversing a Dictionary

We can access each item of the dictionary or traverse a dictionary using for loop.

Method 1

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}

for key in dict1:

print(key , ':‘ , dict1[key])

Output

Mohan: 95

Ram: 89

Suhel: 92

Sangeeta: 85

21 of 34

Traversing a Dictionary

  • Method 2
  • >>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}

for key,value in dict1.items():

print(key,':',value)

Output

Mohan: 95

Ram: 89

Suhel: 92

Sangeeta: 85

22 of 34

Dictionary Operations – �Membership operator – in

The membership operator in checks if the key is present in the dictionary and returns True, else it returns False.

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}

>>> 'Suhel' in dict1

True

23 of 34

Dictionary Operations – �Membership operator – not in

The not in operator returns True if the key is not present in the dictionary, else it returns False.

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}

>>> 'Suhel' not in dict1

False

​

24 of 34

Dictionary Methods and Built-in Functions

Method

Description

Example

len()

Returns the length or number of key: value pairs of the dictionary passed as the argument

>>> dict1 = {'Mohan':95,'Ram':89,

'Suhel':92, 'Sangeeta':85}

>>> len(dict1)

4

dict()

Creates a dictionary from a

sequence of key-value pairs

pair1 = [('Mohan',95),('Ram',89),

('Suhel',92),('Sangeeta',85)]

>>> pair1

[('Mohan', 95), ('Ram', 89), ('Suhel', 92), ('Sangeeta', 85)]

>>> dict1 = dict(pair1)

>>> dict1

{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}

get()

Returns the value corresponding to the key passed as the argument

If the key is not present in the

dictionary it will return None

>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}

>>> dict1.get('Sangeeta')

85

>>> dict1.get('Sohan')

>>>

25 of 34

Dictionary Methods and Built-in Functions

Method

Description

Example

keys()

Returns a list of keys in

the dictionary

>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}

>>> dict1.keys()

dict_keys(['Mohan', 'Ram', 'Suhel', 'Sangeeta'])

values()

Returns a list of values in

the dictionary

>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}

>>> dict1.values()

dict_values([95, 89, 92, 85])

items()

​

Returns a list of tuples(key –

value) pair

>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}

>>> dict1.items()

dict_items([( 'Mohan', 95), ('Ram', 89), ('Suhel', 92), ('Sangeeta', 85)])

clear()

Deletes or clear all the items of

the dictionary

>>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92, 'Sangeeta':85}

>>> dict1.clear()

>>> dict1

{ }

26 of 34

Dictionary Methods and Built-in Functions

Method

Description

Example

update()

appends the key-value pair of the dictionary passed as the argument to the key-value pair of the given dictionary

>>> dict1 = {'Mohan':95, 'Ram':89,

'Suhel':92, 'Sangeeta':85}

>>> dict2 = {'Sohan':79,'Geeta':89}

>>> dict1.update(dict2)

>>> dict1

{'Mohan': 95, 'Ram': 89, 'Suhel': 92,

'Sangeeta': 85, 'Sohan': 79, 'Geeta': 89}

>>> dict2

{'Sohan': 79, 'Geeta': 89}

popitem()

​

It will remove the last dictionary item and return key,value. of the removed item

​

>>> dict1 = {'Mohan':95, 'Ram':89,

'Suhel':92, 'Sangeeta':85}

>>> k,v = dict1.popitem()

>>> print(k,”: “ v)

Sangeeta :85

copy()

it will create a copy of dictionary.

>>> dict1 = {'Mohan':95, 'Ram':89,

'Suhel':92, 'Sangeeta':85}

>>> dic2 = dict1.copy()

27 of 34

Dictionary Methods and Built-in Functions

Method

Description

Example

fromkeys()

return new dictionary with the given set of elements as the keys of the dictionary.

​

Note:

Set of elements should be immutable type

>>>seq = ('name', 'age', 'sex')

>>>dict = dict.fromkeys(seq)

>>>print ("New Dictionary : “ , str(dict) )

​

New Dictionary : {'age': None, 'name': None, 'sex': None}

>>>dict = dict.fromkeys(seq, 10)

>>>print ("New Dictionary : " , str(dict) )

New Dictionary : {'age': 10, 'name': 10, 'sex': 10}

setdefault()

returns the value of the item with the specified key.

If the key does not exist, insert the key, with the specified value,

​

>>>car = { "brand": "Ford", “model": "Mustang", "year": 1964 }�>>>x = car.setdefault("color", "white“)�>>>print(x)

white

28 of 34

Dictionary Methods and Built-in Functions

Method

Description

Example

sorted()

this function is used to sort the key or value of dictionary in either ascending or descending order. By default it will sort the keys.

​

To display in descending order

>>> Dict1 = {1: 111, 4: 444 , 3: 300, 5: 555 , 2: 222}

>>> print(sorted(Dict1))

{1: 111, 2: 222, 3: 300, 4: 444, 5: 555}

​

>>>print(sorted(Dict1, reverse = ‘True’))

{5:555,4:444, 3:333 , 2:222 , 1:111}

min()

This function returns lowest value in dictionary, this will work only if all the values in dictionary is of numeric type

​

>>> Dict1 = {1: 111, 4: 444 , 3: 300, 5: 555 , 2: 222}

>>>print(min(Dict1.values()))

111

​

max()

This function returns highest value in dictionary, this will work only if all the values in dictionary is of numeric type

​

>>> Dict1 = {1: 111, 4: 444 , 3: 300, 5: 555 , 2: 222}

>>>print(max(Dict1.values()))

555

29 of 34

SUGGESTED PROGRAMS

30 of 34

Program 1

#Count the number of times a character appears in a given string

st = input("Enter a string: ")

dic = {} #creates an empty dictionary

for ch in st:

if ch in dic: #if next character is already in the dictionary

dic[ch] += 1

else:

dic[ch] = 1 #if ch appears for the first time

for key in dic:

print(key,':',dic[key])

​

Output:

Enter a string: HelloWorld

H : 1

e : 1

l : 3

o : 2

W : 1

r : 1

d : 1

​

​

31 of 34

Program 2

#Program to create a dictionary which stores names of the employee and their salary

num = int(input("Enter the number of employees whose data to be stored: "))

count = 1

employee = dict() #create an empty dictionary

while count <= num:

name = input("Enter the name of the Employee: ")

salary = int(input("Enter the salary: "))

employee[name] = salary

count += 1

print (‘\nDetails of Employees ‘)

print("\n\nEMPLOYEE_NAME\tSALARY\n~~~~~~~~~~~~~~~~~")

for k in employee:

print(k,'\t\t',employee[k])

32 of 34

Output

Enter the number of employees to be stored: 5

Enter the name of the Employee: 'Tarun'

Enter the salary: 12000

Enter the name of the Employee: 'Amina'

Enter the salary: 34000

Enter the name of the Employee: 'Joseph'

Enter the salary: 24000

Enter the name of the Employee: 'Rahul'

Enter the salary: 30000

Enter the name of the Employee: 'Zoya‘

Enter the salary: 25000

​

Details of Employees

EMPLOYEE_NAME SALARY

~~~~~~~~~~~~~~~~~~~~~~~~~~

'Tarun' 12000

'Amina' 34000

'Joseph' 24000

'Rahul' 30000

'Zoya' 25000

33 of 34

Summary

​

  • Dictionary is a mapping (non-scalar) data type.
  • It is an unordered collection of key-value pair; keyvalue pair are put inside curly braces.
  • Each key is separated from its value by a colon.
  • Keys are unique and act as the index.
  • Keys are of immutable type but values can be mutable.
  • We can add an item, modify an item in a dictionary;
  • Functions/methods used in Dictionary are – len(), dict(), keys(), values(), items(), get(), update(), del(), del, clear(), fromkeys(), copy(), pop(), popitem(), setdefault(), max(), min(), sorted().

​

34 of 34

BIBLIOGRAPHY:

1. Computer Science Textbook for class XI

by NCERT

2. Computer Science with Python

by Sumita Arora

3. Computer Science with Python

by Preeti Arora