Search code examples
python-3.xlistdictionary-comprehension

Why the output is different in this list comprehension?


When I Execute the following code it works correctly:

hassam="CHECK"
list1={i:hassam[i] for i in range(5)}
list1

output:

{0: 'C', 1: 'H', 2: 'E', 3: 'C', 4: 'K'}

but when i execute this:

hassam="CHECK"
list1={hassam[i]:i for i in range(5)}
list1

output:

{'C': 3, 'H': 1, 'E': 2, 'K': 4}

why isnt this:

{'C': 1, 'H': 2, 'E': 3,'C' : 4 ,'K': 5}

Solution

  • For the dictionary :

    {0: 'C', 1: 'H', 2: 'E', 3: 'C', 4: 'K'} 
    

    the numbers being the key is not same.
    But for the dictionary

    {'C': 1, 'H': 2, 'E': 3,'C' : 4 ,'K': 5}
    

    python doesn't allow duplicate keys. Therefore the key is updated with the new value.
    Here, it showed so because dictionaries cannot have same keys with diffrent values. So try using list1 as a list like:

    list1=[{hassam[i]:i} for i in range(5)]
    

    This would give:

    [{'C': 0}, {'H': 1}, {'E': 2}, {'C': 3}, {'K': 4}]
    

    Or a tuple instead of individual dictionaries:

    list1=[(hassam[i],i) for i in range(5)]