How to use a variable in a dictionary before declaring it?
Question:
To guess a user’s password I need to use each password in a loop:
for password in passwords_list:
do_something_with_the_password({'Username': 'Joe', 'Password': password})
I get the dictionary {'Username': 'Joe', 'Password': password}
from user input so need to use password
variable before declaring it. I tried placeholders like password = None
then declaring in the loop:
password = None
data = {'Username': 'Joe', 'Password': password} ## Got from user input
for password in passwords_list:
data['Password'] = password
do_something_with_the_password(data)
The loop is huge and using multiprocessing accessing dictionary is troubling. I tried eval()
but it significantly slowed my program. How to do this successfully?
data = {'Username': 'Joe', 'Password': password}
for password in passwords_list:
do_something_with_the_password(data) ## With it actually using the password, for that specific loop, in the dictionary
Answers:
If I understand what you’re asking correctly, you’re trying to dynamically set the key/value pairs of a dictionary in a for loop(?).
password_list = ["password", "password123"] # etc
# i.e. "Username"
key1 = input("First key")
# i.e. "Joe"
val1 = input("First val")
# i.e. "Password"
key2 = input("Second key")
for password in password_list:
data = {key1: val1, key2: password}
do_something(data)
Python will automatically insert "Username" for key1
, "Joe" for val1
, and "Password" for key2
To guess a user’s password I need to use each password in a loop:
for password in passwords_list:
do_something_with_the_password({'Username': 'Joe', 'Password': password})
I get the dictionary {'Username': 'Joe', 'Password': password}
from user input so need to use password
variable before declaring it. I tried placeholders like password = None
then declaring in the loop:
password = None
data = {'Username': 'Joe', 'Password': password} ## Got from user input
for password in passwords_list:
data['Password'] = password
do_something_with_the_password(data)
The loop is huge and using multiprocessing accessing dictionary is troubling. I tried eval()
but it significantly slowed my program. How to do this successfully?
data = {'Username': 'Joe', 'Password': password}
for password in passwords_list:
do_something_with_the_password(data) ## With it actually using the password, for that specific loop, in the dictionary
If I understand what you’re asking correctly, you’re trying to dynamically set the key/value pairs of a dictionary in a for loop(?).
password_list = ["password", "password123"] # etc
# i.e. "Username"
key1 = input("First key")
# i.e. "Joe"
val1 = input("First val")
# i.e. "Password"
key2 = input("Second key")
for password in password_list:
data = {key1: val1, key2: password}
do_something(data)
Python will automatically insert "Username" for key1
, "Joe" for val1
, and "Password" for key2