ChangeMyName
ChangeMyName

Reputation: 7408

Why the size of list reduced after being converted to dictionary in Python?

I have a list which is composed of tuples where the employee is unique:

my_list = [(Decimal('679.666666'), 'Employee1'), (Decimal('792.000000'), 'Employee2'),...]

and I've made it to dictionary by using:

new_dict = dict(my_list)

However, I found the size of the object has been reduced after it is converted to dictionary (len(my_list) = 404, len(new_dict) = 353)

I have no idea why this is happening. Can anyone let me know what is wrong?

Many thanks.

Upvotes: 2

Views: 74

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90909

When you convert a list of tuples to a dictionary, the first value of the tuple is taken as the key in the dictionary, and the second value as the value.

Most probably there are tuples where the first value is equal to the first value of some other tuples, and hence in those cases the values get overwritten by the tuples that come later. And hence this would be the reason why the dictionary size is lesser than the list size.

Example to show this -

>>> l = [(1,2),(2,3),(1,4)]
>>> dict(l)
{1: 4, 2: 3}

Upvotes: 4

Related Questions