Search code examples
python-3.xlistdictionarylogic

Can someone explain the logic behind this code?


a = [1,2,3,4,4,2,2]
d = {k: v for v, k in enumerate(a)}
print(d)

Let me rephrase myself.

from the above code what does this line exactly mean.

{k: v for v, k in enumerate(a)}

Solution

  • #i have added  10 as a last item in your list for easy understanding.
    a = [1,2,3,4,4,2,2,10]
    d = {k: v for v, k in enumerate(a)} #this is a dictionary comprehension
    print(d)
    
    where 'k' returns the items in the list one by one and 'v' returns the count for 
    each item in list starting from 0.
    like k-->v
     1-->0
     2-->1
     3-->2
     4-->3
     4-->4
     2-->5
     2-->6
     10-->7
    The output is {1: 0, 2: 6, 3: 2, 4: 4, 10: 7}
    as you know dictionary doesnt allow duplicate keys. when any duplicate key 
    arrives it rewrites the previous one and holds the latest one.
    
    {1: 0, 2: 6, 3: 2, 4: 4, 10: 7}
    as we have 1 in only once in the input list we get 1:0
    and for 2 we have three values 1,5,6 as 6 is the latest value. we get 
    2:6
    Like wise happens.