Python Forum
How does this code know to use the key of a dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How does this code know to use the key of a dictionary
#1
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?
Reply
#2
(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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Dictionary within html code ebolisa 4 2,542 Aug-09-2021, 11:36 AM
Last Post: ebolisa
  Iterating over a dictionary in a for loop - checking code has worked sallyjc81 1 1,881 Dec-29-2020, 05:14 PM
Last Post: ndc85430
  Line of code to show dictionary doesn't work MaartenRo 2 2,397 Jul-28-2020, 03:58 PM
Last Post: deanhystad
  Why does my code not execute? (def function with 'for in' iteration over a dictionary Placebo 3 2,882 Oct-19-2018, 01:32 PM
Last Post: Placebo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020