I am trying to write a password generator. Here is part of the code I write below:
import random
total_length = 12
limit = int(total_length / 4)
special_characters = random.randint(1, limit)
upper_case = random.randint(1, limit)
integers_num = random.randint(1, limit)
sums = special_characters upper_case integers_num
lower_case = total_length - sums
integers_sum = [str(a) for a in range(0, 10)]
special_characters_sum = [r'/', r'*', r'-', r' ', r'@']
upper_case_sum = [chr(i) for i in range(65, 91)]
lower_case_sum = [chr(i) for i in range(97, 123)]
pwd_dict = {}
pwd_dict[integers_num] = integers_sum
pwd_dict[special_characters] = special_characters_sum
pwd_dict[upper_case] = upper_case_sum
pwd_dict[lower_case] = lower_case_sum
What confused me is that the length of the 'pwd_dict' should be 4, but actually dict length varies from 2 to 4 when runs that code. Hoping someone can help me to figure out why this happens.
I want to create a dict, and use for loops to generate password string (keys are loop times and key.items to be picked ), then sort the string randomly
CodePudding user response:
Considering:
special_characters = random.randint(1, limit)
upper_case = random.randint(1, limit)
integers_num = random.randint(1, limit)
and
pwd_dict = {}
pwd_dict[special_characters] = special_characters_sum
pwd_dict[upper_case] = upper_case_sum
pwd_dict[lower_case] = lower_case_sum
It seems that you are using randomly generated integers as your dictionary keys. A python dictionary can only contain unique keys hence in the cases where your keys are the same, the value of a specific key will be replaced instead of a new key/value pair being created.
Furthermore, I don't believe you are interested in using numerical values as keys? You are likely trying to use "lower_case" as a string key instead.