Professional Documents
Culture Documents
Dictionaries
Dictionaries
>>> 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'}
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.
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
>>> 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:
>>> 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'}
>>> 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'
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)
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'}
[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)
Output:
1 One
3 Three
2 Two
>>> d1={1:'One',2:'Two'}
>>> d2={3:'Three',4:'Four'}
>>> d3={5:'Five',6:'Six'}
>>> d={**d1,**d2,**d3}
>>> d
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.
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)
#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:
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)
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)
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:
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%
)