[Tutor] Possible usage of dict comprehensions

Mats Wichmann mats at wichmann.us
Mon Oct 19 19:36:38 EDT 2020


On 10/19/20 5:19 PM, Manprit Singh wrote:
> Dear sir ,
> 
> Assume I am using Python 3.7 or later, in which dictionary insertion order
> is maintained. If I want to remove duplicates from a list while maintaining
> the order of its elements, doing like this is a valid and a useful use case
> ?
> 
>>>> l = [2, 4, 5, 3, 4, 5, 2, 1]   # List whose duplicates have to be
> removed
>>>> list({i:None for i in l})
> [2, 4, 5, 3, 1]                   # Resultant list with duplicates removed
> , order preserved

Yes, but note that what you have written exists as the fromkeys() method
already:

list(dict.fromkeys(I))

You can fall back to a dict comprehension if you want the values to not
all be the same object, but since you don't care about the values,
fromkeys is fine.


More information about the Tutor mailing list