Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python dictionary length not as supposed

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading