Python Forum

Full Version: Why is dictionary length not 20?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

Here's some code:

test_keys = []

for i in range(0,20):
    n = random.randint(1,20)
    test_keys.append(n)
#print(randomlist)

numbers = range(0,20)
#test_values = [number for number in numbers]
test_values = []
for j in numbers:
    m = random.randint(1,20)
    test_values.append(m)
new_dict = {test_keys[k]: test_values[k] for k in range(len(test_keys))}

print(f'Dictionary has been compliled with length {len(new_dict)}.')
print(f'Length of test_keys is {len(test_keys)}')
print(f'Length of test_values is {len(test_values)}')
print(f'test_values is:{test_values}')
print(f'test_keys is:{test_keys}')
print(new_dict)
If I run this several times, len(new_dict) changes and it's never 20 as I would expect.

What did I do wrong?

Thanks,
Mark
Dictionaries hold values for unique keys. It cannot have duplicate keys. Every time one of your keys is repeated, only the last value for it is kept.

This dictionary is created with 3 keys, but since one is repeated, there are only 2 keys in the dictionary at the end.

>>> keys = [4, 4, 5]
>>> values = [1, 2, 3]
>>> new_dict = dict(zip(keys, values))
>>> new_dict
{4: 2, 5: 3}
Thank you!