Python Forum

Full Version: How does this code know to use the key of a dictionary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am going though Automate the boring stuff with Python and in a section manipulating strings, there is this script:

# this program is an insecure password locker

PASSWORDS = {'email': 'incospmei#$%', 'blog': 'hycnopL%(', 'luggage': '12345'}

import sys, pyperclip

if len(sys.argv) < 2:
  print('Usage: python password.py [account] - copy account password')
  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 name ' + account + '.')
My question is, how does the program know that I want the key returned from the variable account? How could I use the key and return the value?
(Feb-15-2020, 08:13 PM)renveg Wrote: [ -> ]My question is, how does the program know that I want the key returned from the variable account? How could I use the key and return the value?

if you enter in the command line python password.py email,
the 'account' variable (line #11) will be set to email (a string). Further, the program checks if the record named 'email' exists in PASSWORD dictionary and tries to get corresponding password for the account (email): PASSWORD[account]. pyperclip.copy is copying the value of password (in case of 'email' account it would be 'incospmei#$%') to clipboard. Finally, you get information that password was copied (line #15). Hope that helps.