Dictionary in Python | CBSE Class 11 | Computer Science
Dear Class 11th STUDENTS, ! Welcome to this tutorial of Dictionary in python from your CBSE class 11 of Computer Science Syllabus .
In this tutorial, we shall be learning our chapter-11: Dictionary in python from Unit 2: Programming and Computational Thinking (PCT-1) as CBSE BOARD suggested to learn about computer system and its organisation to complete this section.
Unit 2: Programming and Computational Thinking (PCT-1)
Chapter : Dictionary in python:
- Introduction,
- Accessing items in a dictionary using keys,
- Mutability of a dictionary (adding a new term, modifying an existing item),
- Traversing a dictionary,
- Built-in functions/methods – len(), dict(), keys(), values(), items(), get(), update(), del, clear(), fromkeys(), copy(), pop(), popitem(), setdefault(), max(), min(), sorted();
- 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.
I advice you to check the latest syllabus given by CBSE Board at its Official website: www.cbseacademic.nic.in
Also, in this tutorial we will covers all necessary topics/concepts required to complete your exams preparations in CBSE classes 11th.
Also, you can Sign Up our free Computer Science Courses for classes 11th and 12th.
NOTE:
- We are also giving some important Questions & Answers for better understanding as well as preparation for your examinations.
- You may also download PDF file of this tutorial from our SHOP for free.
- For your ease and more understanding, we are also giving the video explanation class of each and every topic individually, so that you may clear your topics and get success in your examinations.
INTRODUCTION
You must have realized that Python offers many different ways to organize collections (i.e., a bunch of values in a single ‘’variable’’) of data items, such as strings, lists, dictionaries, tuples etc. Of these you have already worked with strings, lists and tuples in previous chapter. Now is the time to work with other collection types. So, in this chapter, we shall be talking about dictionaries.
In this chapter, you shall be learning about how data-items are organized in a Python dictionary, how you can access items from a dictionary, various operations that you can perform on a dictionary and various related functions and methods.
DICTIONARY – KEY: VALUE PAIRS
Among the built -in Python data types is very versatile type called dictionary. Dictionaries are simply another type of collection in Python, but with a twist. Rather than having an index associated with each data-item (just like in lists or strings), Dictionaries in Python have a ‘’key’’ and a ‘’value of that key’’. That is, Python dictionaries are a collection of some key-value pairs.
Do not get confused, just read on. Just like in English dictionaries you can search for a word’s meaning, because for each word there is a meaning associated with it. In the same manner, Python dictionaries have some keys (just like English dictionaries have words) and associated values (just like English dictionaries have associated meanings for every word).
Dictionaries are containers that associate keys to values. This is, in a way, similar to lists. In lists, you must remember the index value of an element from the list, but with the case of dictionaries, you’ll have to know the key to find the element in the dictionaries. All this will become clear to you while you go through following sections.
All this will become clear to you while you go through following sections.
Creating a Dictionary
To create a dictionary, you need to include the key: value pairs in curly braces as per following syntax
<dictionary-name> = {<key>: <value>, <key>: <value> …}
Following is an example dictionary by the name teachers that stores the names teachers as keys and the subjects being taught by them as values of respective keys.
teachers = { ‘’Dimple’’ : ‘’Dimple’’ : ‘’Computer Science’’, ‘’karen’’ : ‘’Sociology’’ ,
‘’Harpreet’’: ‘’Mathematics’’, ‘’Sabah’’: ‘’legal Studies’’}
Notice that
- The curly brackets mark the beginning and end of the dictionary,
- Each entry (key: Value) consists of a pair separated by a colon- the key are corres-ponding value is given by writing colon (:) between them,
- The key – value pairs are separated by commas (,).
As you can see that there are four key: vale pairs in above dictionary. Following table illustrates the key- value relationships in above dictionary teachers.
Consider some more dictionary declarations:
Dict1 = {} # it is an empty dictionary with no elements
DaysInMonths = {‘’January’’: 31, ‘’February’’: 28, ‘’March’’: 31, ‘’April’’: 30, May: 31,
‘’June’’: 30, ‘’July’’: 31, ‘’September’’: 30, ‘’October’’: 31,
‘’August’’: 31, ‘’September’’: 30, ‘’October’’: 31, ‘’November’’: 30, ‘’December’’ 31}
Bird Count = { ‘’Finch’’ : 10, ‘’Myna’’ : 13, ‘’Parakeet’’ : 16, ‘’Hornbill’’ : 15, ‘’Peacock’’ : 15 }
Now you can easily identify the keys and corresponding values form above given dictionaries.
One thing that you must know is that keys of a dictionary must be of immutable types such as.
If you try to given a mutable type as key, Python will give you an error as: ‘’unhashable type see below:
>>>dict3 = {[2,3]: ‘’abc’’}
:
TypeError: unshushable type: ‘list’
Accessing Elements of a Dictionary
While accessing elements from a dictionary, you need the key. While in lists, the elements are accessed through their index; in dictionaries, the elements are accessed through the keys defined in the key : value pairs, as per the syntax shown below :
<Dictionary-name> [ <key>]
Thus to access the value for key defined as ‘’Karen’’ in above declared teachers dictionary, you will write:
>>>teachers[‘’Karen’’]
And Python will return
Sociology
Similarly, following statement
>>>print (‘’Karen teaches’’, teachers [ ‘’karen’] )
Will give output as:
Karen teaches Sociology
While giving key inside square brackets gives you access only to the value corresponding the mentioned key, mentioning the dictionary name without any square brackets’ prints/displays the entire contents of the dictionary.
Consider following example:
As per above examples, we can say that key order is not guaranteed in Python. This is because in Python dictionaries, the elements (key : value pairs) are unordered; one cannot access element as per specific order. The only way to access a value is through key. Thus we can say that keys act like indexes to access values from a dictionary.
Also, attempting to access a key that doesn’t causes an error. Consider the following statement that is trying to access a non-existent key (13) from dictionary d.
>>> d [13]
Traceback (most recent call last) :
File ‘’<pyshell#7>’’, line1, in <module>
d keyError :13
[13]
The above error means that before we can access the value of a particular key using expression such as d[‘’13’’], we must first ensure the key (13 here) exists in the dictionary {‘’goose’’ : 3, ‘’tern’’ : 3, ‘’hawk’’ : 1 }
Figure 13.1 reference of keys and values are stored in a dictionary
Like list elements, the keys and values of a dictionary are stored through their references
Figure above llustrates the same for dictionary {“goes”: 3,”tern” : 3, “hawk” : 1}
Traversing a Dictionary
Traversal of a collection means accessing and processing each element of it. Thus traversing dictionary also means the same and same is the tool for it ,i.e, the Python loops.
The for loop makes it easy to traverse or loop over the items in a dictionary, as per following syntax:
For <item>in <Dictionary> :
Process each item here
The loop variable <item> will be assigned the keys of <Dictionary> one by one, (just like they are assigned indexes of strings or lists while traversing them), which you can use inside the body of the for loop.
Consider following example that will illustrate this process. A dictionary namely d1 is defind with three keys- a number, a string, a tuple of integers.
As per above output, loop-variable key will be assigned ‘a’ in first iteration and hence the key ‘’a’’ and its value ‘’string’’ will be printed ; in second iteration, key will get element (1,2) and its value ‘tuple’ will be printed along with it ; and so on.
So, you can say that traversing all collection is similar. You can use a for loop to get hold of indexes or keys and then print or access corresponding values inside the loop-body.
Accessing Keys or Values Simultaneously
To see all the keys in a dictionary in one go, you may write <dictionary>.keys () and to see all values in one go, you may write <dictionary>.values( ), as shown below (for the same dictionary d created above ) :
>>> d. keys ()
dict_keys ( [‘Vowel5’, Vowel4’, Vowel3’, ‘Vowel2’, ‘Vowel1’] )
>>> d. values ()
dict_ values ([‘u’, ‘o’, ‘i’, ‘e’, ‘a’] )
As you can see that the keys () function returns all the keys defined in a dictionary in the from of a sequence and also the values()function returns all the values defined in that dictionary in the form of a sequence.
You can convert the sequence returned by keys () and values () functions by using list () as shown below:
>>>list (d. keys ())
[‘Vowel5’, ‘Vowel4’, ‘Vowel3’, ‘Vowel2’, ‘Vowel1’]
>>>list (d. values ())
[‘u’, ‘o’, ‘I’, ‘e’, ‘ a’ ]
Characteristics of a Dictionary
Dictionaries like lists are mutable and that is the only similarity they have with lists. Otherwise, dictionaries are different type of data structures with following characteristics :
Unordered set
A dictionary is a unordered set of key: value pairs .Its values can contain references to any type of object.
Not a sequence
unlike a string, list and tuple, a dictionary is not a sequence because it is unordered set of elements. The sequence is indexed by a range of ordinal numbers. Hence they are ordered, but a dictionary is an unordered collection.
Indexed by keys , Not Number
Dictionaries are indexed by keys . According to python, a key can be “ any non-mutable type .” Since strings and numbers are not mutable, you can use them as a key in a dictionary. And if a tuple contains immutable objects such as integers or string etc., then only it can also be used as a key. but the values in a dictionary can be any type , and types can be mixed within one dictionary . Following dictionary dict 1 has keys of different immutable types:
keys must be unique
Each of the keys within a dictionary must be unique. since keys are used to identify values in a dictionary, there cannot be duplicate keys in a dictionary.
However, two unique keys can have same values, e.g., consider the same Bird count dictionary declared above:
Mutable
like lists, dictionaries are also mutable. We can change the value of a certain key “ in place” using the assignment statement as per syntax :
< dictionary > [<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 simple changed as in the assignment statement above.
>>> dict1 [“new”] = “a new pair is added”
>>> dict1
{ 0 : “value for key 0’, 1 : ‘value for key 1’, (4, 5 ] : ‘value for a
tuple –as- a-key : ‘value for a string –as-a- key’, ‘and for fun’ : 7 ,
‘new : ‘a new pair is added’ }
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.
WORKING WITH DICTIONRIES
After basics of dictionaries, let us discuss about various operations that you can perform on dictionaries, such as adding elements to dictionaries, updating and deleting elements of dictionaries. This section is dedicated to the same.
Multiple Ways of Creating Dictionaries
you have learnt to create dictionaries by enclosing key: value pairs in curly braces. There are other ways of creating dictionaries too that we going to discuss here.
1 Initializing a Dictionary
In this method all the key: value pairs of a dictionary are written collectively, separated by commas and enclosed in curly braces.
You have already worked with this method. All the dictionaries created so far have been created through this method, e.g., following dictionary Employee is also being created the same way:
Employee = {‘name’: ‘john’, ‘salary’: 10000, ‘age’: 24}
Adding key: value pairs to an Empty Dictionary
in this method, firstly an empty dictionary is created and then keys and values are added to it one pair at time.
To create an empty dictionary , there are two ways :
- (1) by giving dictionary contents in empty curly braces as shown below :
Employees = { }
(2) by using dictionary constructor dict ( ) as shown below :
Employee = dict ( ) - Next step is to add key: value pairs, one at a time as per syntax given below:
<dictionary > [ <key >] = <value>
For example, in the adjoining statements we are first adding a key: value pair of ‘names’: ‘john’, next statements add value 10000 for key ‘salary’ and the third and last statement adds value 24 for key ‘age’.
This method of creating dictionaries is used to create dictionaries dynamically, at runtime
3. Creating a Dictionary from name and value pairs
Using the dict () constructor of dictionary, you can also create new dictionary initialized from specified set of keys and values. There are multiple ways to provide keys and values to dict () constructor.
(1) Specify key: value pairs as keyword arguments to dict () function, keys as arguments and values as their values. Here the argument names are taken as keys of string type
The zip function clubs first value from first set with the first value of second set, second value from first set with the second value of second set, and so on, e.g., in above example, ‘name’ is clubbed with ‘john’, ‘salary’, with 10000 and ‘age’ with 24. Using these clubbed values, the dict () constructor method creates key: value pairs for the dictionary.
(4) specify key: value pairs separately in form of sequences. In this method, one list or tuple argument is passed to dict (). This argument (passed list or tuple) contains lists / tuples of individual key: value pairs.
That is, a key: value pair is specified in the form of a list and there are as many lists as items of the outer list as there are key: value pairs in the dictionary.
Consider the following example:
You can also pass a tuple containing key: value pairs as list – element or tuples as elements. See following examples:
Adding elements of a dictionary
You can add new elements (key: value Pair) to a dictionary using assignment as per following syntax. But the key being added must not exist in a dictionary and must be unique if the key already exists then statement will change existing key no new entry will be added to dictionary.
<dictionary> [<key>] = <value>
Consider the following example
Nesting dictionaries
You can even add dictionaries as value inside a dictionary. program 13.2 uses such a dictionary. Storing a dictionary inside another dictionary is called nesting of dictionaries. but one thing you must know about nesting of dictionaries is that, you can store a dictionary as value only, inside a dictionary type; you know the reason only immutable type can form the key of a dictionary.
Example: A dictionary contains details of two workers with their names as keys and other details in the form of dictionary as value. Write a program to print the worker’s information in records format.
Employees = {‘john’: {‘age’: 25, ‘salary’: 20000}, ‘Diya’: {‘age’: 35, ‘salary’: 50000} }
For key in employees:
Print (“Employee”, key, ‘:’)
Print (‘Age:’, str (Employees [key] [‘age’] ) )
Print (‘salary:’, str (Employees [key] [‘salary’] ) )
Employee john:
Age: 25
Salary: 20000
Employee Diya:
Age: 35
Salary: 50000
Updating existing Elements in a Dictionary
Updating an element is similar to what we did just now. That is, you can change value of an existing key using assignment as per following syntax:
Dictionary >[<key>] = <value>
Consider following example:
>>> Employee = {‘name’: ‘john’, ‘salary’: 10000, ‘age’: 24}
>>>Employee [‘salary’] = 20000
>>>Employee
{‘salary’: 20000, ‘age’ :24, ‘name’: ‘john’}
But make sure that the key must exist in the dictionary otherwise new entry new entry will be added to the dictionary.
Using this technique of adding key: value pairs, you can create dictionaries interactive at runtime by accepting input from user. Following program illustrates this.
Example:
writes a program to create a dictionary containing names of competition winner students as keys and number of their wins as values.
N= int (input (“how many students?”))
Compwinners = { }
for a in range (n):
key = input (“name of the student:”)
value = int (input (“number of competitions won:”) )
compwinners [key] = value
print (“The dictionary now is:”)
print (compwinners)
The sample run of above program is:
How many students? 5
Name of the student : Rohan
Number of competitions won: 5
Name of the student : Zeba
Number of competitions won: 3
Name of the student :Nihar
Number of competitions won: 3
Name of the student :Roshan
Number of competitions won: 1
Name of the student :james
Number of competitions won: 5
The dictionary now is :
{‘Nihar’ : 3, ‘Rohan’ : 5, ‘Zeba’ : 3, ‘Roshan’ : 1, ‘james’ : 5}
Deleting elements from a dictionary
There are two methods for deleting elements from a dictionary.
- To delete a dictionary element or a dictionary entry, i.e., a key value pair, you can use del command. The syntax for doing so is a s given below:
del <dictionary > [<key >]
consider the following example:
- Another method to delete elements from a dictionary is by using pop ( ) method as per following syntax :
<Dictionary>. Pop (<key>)
The pop method will not only delete the key value pair of mentioned key but also return the corresponding value.
Consider the following example
However, pop () method allows you to specify what do display when the given key does not exist, rather the default error message. This can be done as per following syntax:
Checking for Existence of a key
Usual membership operators in and not in work with dictionaries as well. But they can check for the existence of keys only. To check for whether a value is present in a dictionary (called reverse lookup), you need to write proper code for that. (Solved problem 8 is based in reverse lookup.)
To use a membership operator for key’s presence in a dictionary, you may write statement as per syntax given below:
<key> in < dictionary>
<key> not in <dictionary>
- The in operator will return True if the given key is present in the dictionary, otherwise false.
- The not in operator will return True if the given key is not present in the dictionary, otherwise false.
Consider the following examples:
Please remember that the operators in and not in do not apply on values of a dictionary, if you use them with dictionary name directly. That is, if you search for something with in a or not in operator with a dictionary, it will only look for in the keys of the dictionary and not values,
Example:
pretty printing a Dictionary