You are on page 1of 27

6.4.1 Dictionaries.

A dictionary is a composite data structure in python comprising a dynamic set of unordered


key: value pairs where the key values must be unique in a particular dictionary. It is a very
useful built-in data type in Python. It is also known as an associative array or mapping since
it maps a given key to its corresponding value. Thus, it provides a newer flexible way for
organizing and accessing data. It is defined by enclosing a comma separated list of key
followed by colon(:) followed by the corresponding value within a pair of braces as illustrated
below:
>>>
weekday={0:'Sunday',1:'Monday',2:'Tuesday',3:'Wednesday',4:'Thursday',5:'Friday',6:'saturday'}
TypeError: 'dict' object is not callable
>>> weekday[5] # This is how a dictionary value is obtained corresponding to a key.
'Friday'
>>> weekday[0] # Another example of value retrieval
'Sunday'
Here, we observe that a key acts like an index. We can also mix different types of keys in the
same dictionary and different types of values, too. But, the defined keys are immutable. Also,
if the same key is stated with different values, the lastly specified one is kept by the sytem,
ignoring the others. However, the key values may be nested if desired and the nesting can be
done up to any depth as shown in the figure below with simple illustrations:
>>> dict={1:'Ram',2:'Rahim',3:'Ramen',4:'Rashid',3:'Ranesh'}
>>> dict[3]
'Ranesh'
>>> dict2={1:{1:'Ramen',2:'Ranesh',3:'Mahesh'},2:'Anita',3:'Nabanita',4:'Sunita'}
>>> dict2[1]
{1: 'Ramen', 2: 'Ranesh', 3: 'Mahesh'}
>>> dict2[1][3]
'Mahesh'
>>>
dict3={1:{1:'Ramesh',2:'Tapesh',3:{1:'Bhupen',2:'Nripen'}},2:{1:'Akbar',2:'Babar'},3:{1:{1:'Antony'
,2:'John',3:'Bob'}}}
>>> dict3[1][3][2]
'Nripen' can be created with variables also as illustrated below:
A dictionary
>>> x=5;y=7;z=9;dt={1:x,2:y,3:z}
>>> dt[3]
9

We can declare an empty dictionary as follows:

>>> d={}
>>> type(d)
<class 'dict'>
We can also include a trailing comma in after the entries in a dictionary similarly like lists
and tuples . However, the comma is not displayed when the dictionary is printed.This is
illustrated below:

>>> d1={1:'One',2:'Two',}
>>> d1
{1: 'One', 2: 'Two'}

6.4.2 Dictionary creation with the dict() constructor.

The dict() method can also be used to construct a dictionary from sequences of (key,value)
pairs within pairs of parentheses as a list of values within square brackets as illustrated
below:
>>> shapes=dict([(1,'Squares'),(2,'rectangles'),(3,'Triangles')])
>>> shapes
{1: 'Squares', 2: 'rectangles', 3: 'Triangles'}

It may be noted that a dictionary may be used as a very helful data structure. But the task of
a dictionary creation may seem to a boring job of entering data with (key: value) pairs. The
following Python script may be used to get rid of the boring task. Here, the user can enter any
number of (key, value) pairs just as a string like: ‘1a’,’2b’ etc. If we accept the entries by using
the input() method, there will be no need of enclosing the data within quotes. We get the
freedom from typing the entries without quotes and without the colon(:) characters. We
then convert the string into a tuple. We next append this tuple to a list. Finally, we use a
dictionary comprehension to convert the whole list into (key: value) entries in a dictionary.
The following code shows the script for the purpose as explained.

l=[] # This is to create an empty list


while True: # This is to set up an indefinite loop to run any desired number of times
entry=input("Enter a key and the corresponding value separated by space----Press just Enter to
quit=> ")
6.4.3 Salient features of a dictionary in Python
In creating dictionaries, we need to remember three important points as stated below:
 Each key must be unique; otherwise, it will be overridden by the same which
is mentioned later.
 Each key must be hashable(explained below); otherwise the TypeError will
be thrown by the system.
 There is no particular order for the keys.

An object is said to be hashable if it has a hash value(a value generated by an internal


function to use as a unique key) which never changes during its lifetime. The function is:
__hash__() . The hashable objects which are found to be equal must have the same hash
value. This is why, hashability makes an object usable as a dictionary key and as a set
member, because these data structures use the hash value internally. All of Python’s
immutable built-in objects are hashable, while no mutable containers (such as lists or
dictionaries) are so. Objects which are instances of user-defined classes(to be dicussed later)
are hashable by default; so, they all compare unequal, and their hash value is their id().

6.4.4 Modifications in a dictionary


A dictionary may be modified by changing an existing entry, by adding a new entry or by
deleting any desired entry specified through the key. This has been illustrated below with a
new dictionary.

>>> Tiu_students={1234:'Gargi Kar',1235:'Suman Das',1236:'Suman Datta',1237:'Parbin


Baby',1238:'Ismail Hossein'}
>>> Tiu_students[1235]='Suman Dasgupta' # The name corresponding to the key 1235 has been
changed.
>>> Tiu_students[1239]='D Huart' # A new dictionary entry has been inserted.
>>> Tiu_students # Listing of the changed dictionary.
{1234: 'Gargi Kar', 1235: 'Suman Dasgupta', 1236: 'Suman Datta', 1237: 'Parbin Baby', 1238: 'Ismail
If required, we can remove all the entries from a dictionary by using the clear() method as
under:
DictionaryName.clear()

But, this command does not remove the structure of the dictionary. We can add new
elements to again. To remove the structure completely, we use the command:

Del DictionaryName

The following figure illustrates the application of the functions:

>>> diction={1:'Dal',2:'Rice',3:'Spice'}
>>> diction.clear() # All dictionary entries are removed now.
>>> diction # Shows the empty dictionary
{}
>>> diction[1]='Fish' # New entries are being inserted into the dictionary.
6.4.5 Important methods for dictionary type of data

The following methods can be aplied on dictionary type of data for the desired effects for
which they have been built into the Python library:

1. len(dictionary_type_variable): This is to return the length of the


dictionary which equals the number of items in it. Example:
>>> d={1:'a',2:'b'}
>>> len(d)
2
2. str(dictionary_type_variable): Converts the dictionary entries into a
printable version of a string. Example: >>> str(d)
"{1: 'a', 2: 'b'}"
3. dictionary_type_variable.copy(): This function can be used to create a
copy of the dictionary mentioned into a new variable of the same type.
Example:
>>> dc=d.copy()
>>> dc
{1: 'a', 2: 'b'}
4. dictionary_type_variable . fromkeys (sequence_of_Key_values
[,value]) : This method is useful to create a dictionary with a sequence
of keys. Initially, the values corresponding to the keys are set to None
which can then be replaced with appropriate values. If all the keys refer
to the same value, the value can also be specified, although optionally.
The following two figures shows its application in two different ways:
>>> seq=(0,1,2)
>>> dc=dc.fromkeys(seq)
>>> dc
{0: None, 1: None, 2: None}
>>> dc[0]='Ram'
>>> dc[1]='Ravan'
>>> dc[2]='Hizarath'
>>> dc
{0: 'Ram', 1: 'Ravan', 2: 'Hizarath'}

Figure: Creating a dictionary with only keys and updating later.


# Dictionary creation from input values
#dcreate.py
dic={} # A blank dictionary
seq=[] # A blank list.
n=int(input("How many Features to add to your dictionary? "))
for i in range(n):
x=input("Enter a Feature: ") # These are keys
seq.append(x) # A sequence is being created by appending to the blank list
g=input("Enter the Common grade to the features: ")
dic=dic.fromkeys(seq,g) # The dictionary with a sequence keys and a common
value
print(" The created dictionary is: ")
print(dic)

Figure: Python script to create a dictionary by accepting keys as inputs

How many Features to add to your dictionary? 3


Enter a Feature: Reading
Enter a Feature: Writing
Enter a Feature: Drawing
Enter the Common grade to the features: E
Figure: Screen displays when the program above is run.

5. dictionary_type_variable. get(key,default_value): This method


shows the value corresponding to the key from the mentioned
dictionary. If the key is not available in the dictionary then it shows the
default_value. This is illustrated below:

>>> dc
{0: 'Ram', 1: 'Ravan', 2: 'Hizarath'}
>>> dc.get(0)
'Ram'
>>> dc.get(5,'Undefined')
'Undefined'
6. dictionary_type_variable . items() : This function shows all the
(key,value) pairs available in the dictionary. For example:
>>> dc.items()
dict_items([(0, 'Ram'), (1, 'Ravan'), (2, 'Hizarath')])
7. dictionary_type_variable. setdefault(key [, default_value]) : This
function can be used to initialize a dictionary with keys without values
initially with a view to update them later. A default value can, of course,
be specified; but, even if it is not specified, the system fills in the value
locations with the Python keyword None. If the mentioned key is
already a defined one then it shows the corresponding value. The
following code illustrates its use.
>>> d={}
>>> for i in range(5): d.setdefault(i)

>>> d
{0: None, 1: None, 2: None, 3: None, 4: None}
>>> dict.setdefault('Jan')
'31'
>>> D={}
>>> for i in range(5): D.setdefault(i,'Undefined')
'Undefined'
'Undefined'
'Undefined'
'Undefined'
'Undefined'
>>> D
{0: 'Undefined', 1: 'Undefined', 2: 'Undefined', 3: 'Undefined', 4: 'Undefined'}

8. dictionary_type_variable.values() : This method is meant for


displaying only the dictionary values available in it. Example: >>>
D.values()
dict_values(['Undefined', 'Undefined', 'Undefined', 'Undefined',
'Undefined'])
9. dictionary_type_variable.pop(key [,default_value]) : This method
removes a given dictionary entry according to the mentioned key and
shows the corresponding value. The default_value, if mentioned, is
shown when the key is not found in the dictionary. The following figure
depicts some illustrative examples:

>>> D={1:'a',2:'b',3:'c'}
>>> D.pop(3)
'c'
>>> D
{1: 'a', 2: 'b'}
>>> D.pop(3,'Undefined')
'Undefined'
>>> D={1:'a',2:'b',3:'c'}
>>> D.pop(1)
'a'
10. dictionary_type_variable. popitem() : This method removes the last
entry from the dictionary as if the removal is from a stack and the
revoved entry is returned as a tuple. The following figure illustrates its
application:
>>> D
{1: 'a', 2: 'b'}
>>> x=D.popitem()
>>> x
(2, 'b')
>>> x=D.popitem()
>>> x
(1, 'a')
>>> t={}
>>> t.popitem() # Trying to popitem from an empty dictionary.
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
t.popitem()
KeyError: 'popitem(): dictionary is empty'

11. dictionary_type_variable. update(another dictionary or any


iterable with (key, value) pairs like a tuple) : This is very important
method that enables us to join two or more dictionaries into a single
one. We can also use this function to create a new dictionary by
updating a blank dictionary through inputs accepted from the console.
To update with a new pair of values, we write:
Name_of_dictionary_to_be_created.update({key: value})
The following program creates a new dictionary by accepting the entries as inputs from
the terminal.
dt={} # A blank dictionary
n=int(input("How Many Entries to keep in your Dictionary?"))
for i in range(n):x=input("Key?");y=input("Value?");dt.update({x:y})

The figure below shows screen displays when the above script is run:
How Many Entries to keep in your Dictionary?3
Key?23
Value?df
Key?45
Value?nm
Key?76
Value?hj
>>> dt
{'23': 'df', '45': 'nm', '76': 'hj'}
The following Python script allows a user to continue creating a dictionary as long as desired
and also allows to set default values, if the value is not available at the time of creation. Thus,
the script provides fexibility to the user elegantly.
#Newdict.py
dict={}
while True:
x=input("Enter a key---Press just ENTER to terminate=> ")
if len(x)==0:
break
y=input("Enter the corresponding value, if not yet decided press ENTER")
if len(y)==0:
dict.setdefault(x,'Undefined')
else:
dict.update({x:y})
print(dict)

12. Dictionary_name.keys() : This method shows the keys of the named


dictionary. The following figure illustrates its use.
>>> d={1:'a',2:'b',3:'c'}
>>> d.keys()
dict_keys([1, 2, 3])

6.4.6 Iteration over dictionaries


In order to iterate over the dictionary entries, we can make use of two iterators and the
items() method as discussed above. This is illustrated in the figure below:

for i,j in days_in_month.items():print(i,j)


This single line of code will generate the following output:
January 31
February 29
March 31
April 30
May 31
June 30
July 31
August 31
September 30
October 31
November 30
December 31
d = {0:’Sunday’,1:’Monday’,2:’Tuesday’,3:’Wednesday’,4:’Thursday’,5:’Friday’,6:’Saturday’}
for key in d: print(key, d[key])

0 Sunday

1 Monday

2 Tuesday

3 Wednesday

4 Thursday

5 Friday

6 Saturday

The iteration can be done for printing only the key values also as illustrated below:

>>> d={1:'a',2:'b',3:'c'}

>>> print([key for key in d]) # printing using dictionary comprehension

[1, 2, 3]

The days_in_month dictionary can be created by taking the month names from a list.
Moreover, as the number of days in February is different in leap years than other normal
years, a leap year check is also required for the year before creating the dictionary. We can
also create a dictionary with month number: days in the month. The program in Python in the
following figure implements the idea.

days_in_month={}
month_days={}
yr=int(input("Enter year for which days in month is required:=> "))
month_name=['January','February','March','April','May','June','July','August','September','October'
,'November','December']
for i in range(1,13):
days=31 if i in (1,3,5,7,8,10,12)else 30 if i in (4,6,9,11) else 29 if i==2 and (yr%4==0 and yr%100!=0
or yr%400==0) else 28
days_in_month.update({month_name[i-1]:days})
month_days.update({i:days})
The following figure illustrates use of some other iterations over a dictionary.
>>> for k in days_in_month.keys():print(k)
January
February
March
April
May
June
July
August
September
October
November
December
>>> for v in days_in_month.values():print(v)
31
29
31
30
31
30
31
31
30
31
30
31

In the figure below, we show a Python script to count the number of each character occuring
>>>
as a key. The characters are taken from an arbitrary text as defined and shown below:
>>> text='I saw a quick brown fox jumping over a lazy dof'
>>> D={}
>>> for char in text:D.setdefault(char,0);D[char]+=1;print(D)
0
{'I': 1}
0
{'I': 1, ' ': 1}
0
{'I': 1, ' ': 1, 's': 1}
0
{'I': 1, ' ': 1, 's': 1, 'a': 1}
0
{'I': 1, ' ': 1, 's': 1, 'a': 1, 'w': 1}
1
{'I': 1, ' ': 2, 's': 1, 'a': 1, 'w': 1}
1
{'I': 1, ' ': 2, 's': 1, 'a': 2, 'w': 1}
2
{'I': 1, ' ': 3, 's': 1, 'a': 2, 'w': 1}
0
{'I': 1, ' ': 3, 's': 1, 'a': 2, 'w': 1, 'q': 1}
0
{'I': 1, ' ': 3, 's': 1, 'a': 2, 'w': 1, 'q': 1, 'u': 1}
0
{'I': 1, ' ': 3, 's': 1, 'a': 2, 'w': 1, 'q': 1, 'u': 1, 'i': 1}
0
{'I': 1, ' ': 3, 's': 1, 'a': 2, 'w': 1, 'q': 1, 'u': 1, 'i': 1, 'c': 1}
0
{'I': 1, ' ': 3, 's': 1, 'a': 2, 'w': 1, 'q': 1, 'u': 1, 'i': 1, 'c': 1, 'k': 1}
3
{'I': 1, ' ': 4, 's': 1, 'a': 2, 'w': 1, 'q': 1, 'u': 1, 'i': 1, 'c': 1, 'k': 1}
0
{'I': 1, ' ': 4, 's': 1, 'a': 2, 'w': 1, 'q': 1, 'u': 1, 'i': 1, 'c': 1, 'k': 1, 'b': 1}
0
{'I': 1, ' ': 4, 's': 1, 'a': 2, 'w': 1, 'q': 1, 'u': 1, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'r': 1}
0
{'I': 1, ' ': 4, 's': 1, 'a': 2, 'w': 1, 'q': 1, 'u': 1, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'r': 1, 'o': 1}
1
{'I': 1, ' ': 4, 's': 1, 'a': 2, 'w': 2, 'q': 1, 'u': 1, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'r': 1, 'o': 1}
0
{'I': 1, ' ': 4, 's': 1, 'a': 2, 'w': 2, 'q': 1, 'u': 1, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'r': 1, 'o': 1, 'n': 1}
4
{'I': 1, ' ': 5, 's': 1, 'a': 2, 'w': 2, 'q': 1, 'u': 1, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'r': 1, 'o': 1, 'n': 1}
0
{'I': 1, ' ': 5, 's': 1, 'a': 2, 'w': 2, 'q': 1, 'u': 1, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'r': 1, 'o': 1, 'n': 1, 'f': 1}
1
{'I': 1, ' ': 5, 's': 1, 'a': 2, 'w': 2, 'q': 1, 'u': 1, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'r': 1, 'o': 2, 'n': 1, 'f': 1}
0
{'I': 1, ' ': 5, 's': 1, 'a': 2, 'w': 2, 'q': 1, 'u': 1, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'r': 1, 'o': 2, 'n': 1, 'f': 1, 'x': 1}
5
{'I': 1, ' ': 6, 's': 1, 'a': 2, 'w': 2, 'q': 1, 'u': 1, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'r': 1, 'o': 2, 'n': 1, 'f': 1, 'x': 1}
0
{'I': 1, ' ': 6, 's': 1, 'a': 2, 'w': 2, 'q': 1, 'u': 1, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'r': 1, 'o': 2, 'n': 1, 'f': 1, 'x': 1, 'j': 1}
1
{'I': 1, ' ': 6, 's': 1, 'a': 2, 'w': 2, 'q': 1, 'u': 2, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'r': 1, 'o': 2, 'n': 1, 'f': 1, 'x': 1, 'j': 1}
0
{'I': 1, ' ': 6, 's': 1, 'a': 2, 'w': 2, 'q': 1, 'u': 2, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'r': 1, 'o': 2, 'n': 1, 'f': 1, 'x': 1, 'j': 1, 'm': 1}
0
{'I': 1, ' ': 6, 's': 1, 'a': 2, 'w': 2, 'q': 1, 'u': 2, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'r': 1, 'o': 2, 'n': 1, 'f': 1, 'x': 1, 'j': 1, 'm': 1, 'p': 1}
1
{'I': 1, ' ': 6, 's': 1, 'a': 2, 'w': 2, 'q': 1, 'u': 2, 'i': 2, 'c': 1, 'k': 1, 'b': 1, 'r': 1, 'o': 2, 'n': 1, 'f': 1, 'x': 1, 'j': 1, 'm': 1, 'p': 1}
1
{'I': 1, ' ': 6, 's': 1, 'a': 2, 'w': 2, 'q': 1, 'u': 2, 'i': 2, 'c': 1, 'k': 1, 'b': 1, 'r': 1, 'o': 2, 'n': 2, 'f': 1, 'x': 1, 'j': 1, 'm': 1, 'p': 1}
0
{'I': 1, ' ': 6, 's': 1, 'a': 2, 'w': 2, 'q': 1, 'u': 2, 'i': 2, 'c': 1, 'k': 1, 'b': 1, 'r': 1, 'o': 2, 'n': 2, 'f': 1, 'x': 1, 'j': 1, 'm': 1, 'p': 1, 'g': 1}
The output extends few more lines which have not been shown to save space. However, the
output can be shown decently and in sorted sequence if we import pprint module for
printing. The word pprint stands for pretty print.This script has been illustrated below:

import pprint
text='I saw a quick brown fox jumping over a lazy dog'
D={}
for char in text:
D.setdefault(char,0)
D[char]+=1
pprint.pprint(D)

The output is shown in the figure below.


{' ': 10,
'I': 1,
'a': 4,
'b': 1,
'c': 1,
'd': 1,
'e': 1,
'f': 1,
'g': 2,
'i': 2,
'j': 1,
'k': 1,
'l': 1,
'm': 1,
'n': 2,
'o': 4,
'p': 1,
'q': 1,
'r': 2,
's': 1,
'u': 2,
'v': 1,
'w': 2,
'x': 1,
'y': 1,
'z': 1}

6.4.7 Ordered dictionary


A dictionary is said to be an ordered dictionary, if it always maintains the original order of
insertion of the entries into it when iterated over the key. The following figure illustrates the
idea through an example.

from collections import OrderedDict


d = OrderedDict()
d[1]='One'
d[3]='Three'
d[2]='Two'
d
OrderedDict([(1, 'One'), (3, 'Three'), (2, 'Two')])
for key in d:
print(key, d[key])

Output:
1 One
3 Three
2 Two

6.4.8 Merging two or more dictionaries


Two or more dictionaries can be merged by using the **dictionaryName within a pair of
braces to create new dictionary. The ** before the dictionary name is called the unpacking
operator that takes out the key: value entries from the dictionary mentioned to replace the
referencing. This is illustrated in the figure below:

>>> d1={1:'One',2:'Two'}

>>> d2={3:'Three',4:'Four'}

>>> d3={5:'Five',6:'Six'}

>>> d={**d1,**d2,**d3}

>>> d

{1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six'}

6.4.9 Nested Dictionaries


Sometimes, in handling comlicated situations, we need to use dictionaries which contain
further dictionaries. Such a dictionary is called a nested dictionary. The following figure
shows a nested dictionary.

bookstock={'science':{'physics':455,'chemistry':308,'biology':275},'engineering':{'ce':175,'ee':235,'ece':257,'cse':376}}

The following script shows how to access the nested dictionary defined above to determine
total number of books available for each of the streams and the grand total of the stock.

#nesteddic.py
bookstock={'science':{'physics':455,'chemistry':308,'biology':275},'engineering':{'ce':175,'ee':235,'
ece':257,'cse':376}}
totbooks=0
grandtot=0
stream=''
for i,j in bookstock.items():
stream=i
for k in j:
totbooks+=j[k]

print("Total number of books in the library for the students of",stream," is: ",totbooks)
grandtot+=totbooks
print("The Grand total of all stocks is",grandtot)
 Accessing a particular element for printing or updation of a nested dictionary is done
as shown in the example here: bookstock[‘science’][‘physics’] i.e.dic_name[key of the
higher level dictionary][key of the next level dictionary], in general
 The generalized syntax mentioned in the point above for further insertion of elements
or deletion of elements.

6.4.10 Applications of dictionaries

Problem-6.4.10.1. A dictionary contains lists of values against each of the keys as


shown below:

d={'key1':['a','b','c'],'key2':[4,7,1958]}

It is required to generate a list to contain all possible combinations of key: value entries for
dictionaries.
Task Analysis: Here, ‘key1’=’a’ can be combined with ‘key2’=4,7 and 1958; similarly,
‘key1’=’b’ can also be combined with ‘key2’=4,7 and 1958 and so on. The problem requires to
explore all such possibilities.
We first separate all the keys by using the command: keys = d.keys().
We next form a tuple of values by using the command: values = (d[key] for key in keys). If we
print the values, we shall have the following listing: print(tuple(values))
(['a', 'b', 'c'], [4, 7, 1958])
We next make use of itertools.product() function to unpack the values as separate
arguments. The operator * is required before the values variable to be unpacked by the
itertools.product() . The unpacked values can then be returned to the zip() function to
generate the possible combinations of the keys- iterable and unpacked_values iterable as
collection of all paired tuples to the dict() constructor. All these activities can be written by
using a list comprehension. This fulfills our target. The complete script is shown in the figure
below:
import itertools
d={'key1':['a','b','c'],'key2':[4,7,1958]}
keys = d.keys()
values = (d[key] for key in keys)
combinations = [dict(zip(keys, combination)) for combination in itertools.product(*values)]
print( combinations)

The figure below depicts the output of the above program.


[{'key1': 'a', 'key2': 4}, {'key1': 'a', 'key2': 7}, {'key1': 'a', 'key2': 1958}, {'key1': 'b', 'key2': 4},
{'key1': 'b', 'key2': 7}, {'key1': 'b', 'key2': 1958}, {'key1': 'c', 'key2': 4}, {'key1': 'c', 'key2': 7},
{'key1': 'c', 'key2': 1958}]

Problem-6.4.10.2. It is required to create a dictionary as an actual dictionary of


definitions.

#dic.py
dic={}
while True:
w=input("Enter a keyword ")
m=input("Enter the meaning of the word")
dic.update({w:m})
r=input("continue?(y/n)")
if r!='y':
break
Problem-5.4.10.3. It is required to evaluate a Roman number.

Task Analysis: We know that a Roman number consists of one or more of the symbols with
the corresponding values as shown below:

I=1, V=5, X=10, L=50, C=100, D=500 and M=1000.

There are certain rules to evaluate a Roman number into its equivalent decimal number. The
symbols are evaluated from left to right. If the decimal value of a symbol happens to be less
than that of the one to its immediately right then its value is taken to be negative. The value
of the rightmost symbol will always be positive since, there is no symbol to its right.
Accordingly, The value of IV will be calculated as -1+5=4, that of XLI will be: -10+50+1=41. So,
we can make use of the concept of a dictionary to develop the desired script. The script is
shown in the figure below

#Roman.py
romans={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'i':1,'v':5,'x':10,'l':50,'c':100,'d':500,'m
':1000}
while True:
rnum=input("Enter any Roman Number-- To Quit just press ENTER")
if len(rnum)==0:break
l=len(rnum);dnum=0;lst=[]
if l==1:dnum=romans[rnum]
for i in rnum:
lst.append(romans[i])
if l>1:
for j in range(l-1):
if lst[j+1]>lst[j]:
dnum=dnum-lst[j]
else:
dnum+=lst[j]

dnum+=lst[j+1]
print("The equivalent Decimal number is: ",dnum)

Problem-6.4.10.4. A Python script is required to be developed to play a game named


Scrabble that will determine the score of a user on the basis of a given English word.
The score is calculated according to certain point value associated with each letter of
the English alphabet.

Task Analysis: First we accept all the letters of the English alphabet in both upper and
lowercases and a chosen value for each of the letters. The values can be assigned randomly
also as we shall see in the solution of the next problem. Then the participant is asked to enter
any word to try his/her luck. Having accepted the word as input, sum up all the numeric
values of the letters in the word to show as the score of the participant. The program may be
modified to store and show the scores of all the participants together in the way that we
have demonstrated in the program below. The use of the concept of dictionary will make it
an elegant script.

#Scrabble.py
letters={}
print(" Allotment of points to the letters")
for i in range(1,52):
l=input("Enter a letter of the English alphabet:=> ")
v=int(input("Enter its integer ponit:=> "))
letters.update({l:v})
while True:
w=input("Enter any word of your choice....Press just the ENTER key to Quit:=> ")
if len(w)==0:break
score=0
for c in w:
score+=letters[c]
print("Your score is:=> ",score)

Problem-6.4.10.5. A python script is conceived to design a game of cards as described


below:
at the outset of the game, each of the cards in the deck is assigned a randomly
selected number within a given range. Then, the number of partcipants is asked for.
Next, for each of the participants the name is sought and the randomly alotted
number of the tomost card(first card) is taken as the score of the participant. The
participant is given five chances to score each time with shuffled cards; the total score
thus obtained is used as the final score of the participant. The actions are repeated for
each of the participants. Finally, the highest scorer is declared as the winner.

Task Analysis: We know that a deck of cards comprises four sets of cards named as:
Spades,Clubs, Hearts and Diamonds. Each set consists of 13 cards with different values or
images. Thus, a total of 52 cards is required to be assigned with randomly generated numbers
that can give a fortune to a winner. In Python, we can store a deck of cards as a list of
dictionaries. We shall use the dictionary comprehension to write a compact code as
illustrated in the figure below:

#cards.py
import string
import random
deck = [{'cardvalue':random.randint(10,101), 'suitName':c,}
for c in ['spades', 'clubs', 'hearts', 'diamonds'] for i in range(2,14)]
while True:
n=int(input("Enter the number of players to participate-- Enter 0 to Quit:=> "))
if n==0:break
tot_score=0;wining_score=0;winner=''
print(" Dear Player, You will get five chances to win...Let us see what you have scored
now")
player=[]
cardgamblers={}

for i in range(n):
nam=input("Enter your Name please:=> ")
player.append(nam)
for j in range(5):
score=deck[0]['cardvalue']
suit=deck[0]['suitName']
print("Your card is from the suit",suit.capitalize()," and your score for the card is:
",score,"at attempt No.",j+1)
tot_score+=score
random.shuffle(deck)
print("Dear Mr./Ms",player[i].capitalize(),"your total score in five attempts is:
",tot_score)
print("Have a better luck next time, Thanks for participating")
cardgamblers.update({player[i].capitalize():tot_score})
if wining_score<tot_score:
wining_score=tot_score
winner=player[i].capitalize()
print(cardgamblers)
print("The wining score is:=> ",wining_score, ", wow,Congrats to the winner:
",winner,", Have a great day")
Problem-6.4.10.6. A Python script is required to count the frequency of words in a
block of text.

Task Analysis: This is a straightforward method. First, we should convert the text either in
lowercase or in uppercase for recognizing the same word in two different cases. The next
task is to break the whole text into separate words.We next remove all the punctuation
marks like ,;.: from the text so that they are not counted. The next task is to use the words as
the key to a dictionary and the count as the corresponding value which is updated whenever
the same word occurs during the scanning of the words. Now, the dictionary can be printed
to get the result.
#word_frequency.py
from string import punctuation
while True:
text=input(“Enter any text with some frequent words…press just ENTER to Quit”)
text = text.lower()
# Now we need to remove the punctuation symbols in the text with null characters
for p in punctuation:
text = text.replace(p, '')
words = text.split()
# next we build the dictionary of frequencies
d = {}
for w in words:
if w in d:
d[w] = d[w] + 1
else:
d[w] = 1
# For printing in alphabetical order, we need to sort them. So, we put them in a list
items = list(d.items())
items.sort()
for i in items:
print(i)
# For printing in order from the least to the most common one
items = list(d.items())
items = [(i[1], i[0]) for i in items] ‘’’ This list comprehension interchanges within value
pairs’’’
items.sort()
for i in items:
print(i)
6.4.10.7. Let us develop a password manager in Python to store all the
passwords of a user for different websites. The password manager
can be opened by using a master password. We can then copy any
account password to the clipboard and paste it into the website’s
Password field. So, we can get rid of tedious task of memorizing the
passwords of different accounts.

Task Analysis: Our program should be such that it can be run with a command line
argument. The command line argument can be the name of the account such as email,
facebook, twitter etc. On the basis of the supplied name of the account, the password will be
identified and read into the clipboard from where we can copy it to the respective account’s
password field. Our program should also be started with a shebang line so that we can run it
with the latest version of Python. A dictionary data structure will enable us to store the
passwords corresponding to each account_name. Moreover, we need to convert the .py file
to an .exe file. So, we need to have discussion on the process of conversion. The process has
been described below:

Let us now explore the conversion of Python scripts to Windows executable files in four
simple steps. Although there are many ways to do it, we think that the following one will be
simplest.
Step 1: Install cURL
cURL provides a library and command line tool for transferring data using various protocols.
We need it to download the pip package manager in the next step. We can check by running
the following command if we already set it up:

DOS Prompt>curl --version

If the command above returns a curl version, we can skip Step 1. Otherwise,

1. We go to https://curl.haxx.se/dlwiz/?type=bin&os=Win64&flav=-&ver=*&cpu=x86_64
2. We next download the curl package which matches our system's specifications (32-
bit/64-bit)
3. We next unzip the file and go to the bin folder where we can find the curl.exe file.

However, this means that we can only use the curl command in that particular folder. In
order to be able to use the curl command from anywhere on our system, we right-click on
curl.exe, we next click on "Properties" and copy the "Location" value. After that, we right-
click on "My PC" and click on "Properties". This will show the following screenshot. In the
option panel on the left, we select the option "Advanced System Settings" which has been
highlighted in the screenshot below.
In the window that appears, we click "Environment Variables" near the bottom right. It has
been highlighted in the screenshot below.
In the next window, we find and double click on the user variable named "Path", then click on
"New". A new text box will be created in that window; paste the "Location" value of the
"curl.exe" file that we have copied earlier, and then we click on 'OK'.
cURL should now be accessible from anywhere in our system. To confirm our installation, we
can run the command below:
DOS Prompt> curl --version
Let's go to the next step.
Step 2: Install pip
In this step, we will install pip, which is basically a package manager for Python packages. We
need it in the next step to install the pyinstaller library. Most of us might have already set it
up, to check it, we run the following command:
DOS Prompt>pip --version

If the command above returns a pip version, then we can skip the next instructions in this
step; otherwise, we can install pip by running the following two commands in the command
prompt:
DOS Prompt> curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
DOS Prompt>python get-pip.py
That's it. Pip has now been installed to our local machine. We now can run the following
command for confirmation:
DOS Prompt>pip --version
Before moving to the next step, we need to repeat what we did for curl.exe so that we can
access the pip command from anywhere in our machine, but this time we'll be doing so for
"pip.exe".
We hit the Windows key and search for "pip.exe", then right-click on the first search result
and click on "Open File Location", it will take us to the folder in which that file is located. We
next right-click on the "pip.exe" file and then select "Properties". After that, we copy the
"Location" value and paste it in the Path variable just like we did in Step 1.
Step 3: Install PyInstaller
In this step, we'll install pyinstaller using pip. We need pyinstaller to convert our Python
scripts into executable (.exe) files. We just need to copy paste the command below into our
command prompt and run it:
DOS Prompt> pip install pyinstaller
Again, to confirm the installation, we can run the following command to check.
DOS Prompt> pyinstaller -- version
Note: If we have Anaconda installed in our system, then for the conda package manager that
we use, we need to run the following commands in sequence:
DOS Prompt>conda install –c conda-forge pyinstaller
DOS Prompt> conda install –c anaconda pywin32

This step marks the end of all installations. In the next step, we'll be converting our Python
files to an executable with just a single command.
Step 4: Convert Python Files to Executables
This is the last step. We'll use pyinstaller to convert our .py files to .exe with a single
command. So, let's do it!
We open up the command prompt and navigate to the directory that our Python file/script is
located in. Alternatively, we can open that directory using File Explorer, right-click + shift and
then selecting "Open Command Prompt in this folder". Before converting our file,we should
check that the script works as expected. Let's run the script and see if it works fine before
converting it to an executable file. We run the following command on our command prompt:
DOS Prompt> python path_name file_name.py
To create a standalone executable file in the same directory as our Python file, we run the
following command:
DOS PROMPT>pyinstaller - -onefile path_name file_name.py
This instruction might take some time to complete. Upon completion, it will generate three
folders. We can find the executable file in the 'dist' folder. It may be noted that the "onefile"
argument tells pyinstaller to create a single executable file only.
Also, we need to note that if the executable file depends on any other executable files,
like phantomjs, we need to keep them in the same directory as our Python file's directory so
that pyinstaller can include it in the executable.
Now, to run the .exe file, we go to dist directory under the current directory and enter:
..\dist>password ‘email’
The program is executed and gives us the following message:
Password for email copied to clipboard.
Now, if we press the ‘paste’ option, we get the password pasted at the desired place.

#! python3
# pw.py - An insecure password locker program.
PASSWORDS = {'email': 'abcdef*&^%$#@!_24_1960_Friday', 'Facebook':
'abc@*&^%$1989', ‘linkedin’: ‘abc@2008_June_*&^%’, 'luggage_trolley':
'7679'}
import sys, pyperclip
if len(sys.argv) < 2:
print(‘Insufficient Number of Arguments—Try again')
sys.exit()
account = sys.argv[2] # first command line arg is the account name
if account in PASSWORDS: pyperclip.copy(PASSWORDS[account])
print('Password for ' + account + ' copied to clipboard.') else: print ('There is no
account named ' + account)

We may make use of the following batch file to run any .exe file with or without
commandline arguments.

@echo off
set pwd=abc
set /p pass="Enter the Master Password=> "
IF %pass%==%pwd% echo You are on the right track
IF NOT %pass%==%pwd% EXIT
cd dist
set /p var1="Enter the name of your .exe file to run=> "
set /p var2="Enter the arguments, for more than one, put space in between=>"
IF NOT "%var2%"=="" (
%var1% %var2%
) ELSE (
%var1%
)

You might also like