Home > Mobile >  Can someone explain the logic behind this code?
Can someone explain the logic behind this code?

Time:10-26

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)}

CodePudding user response:

First you have enumerate(a). This built-in function adds a counter to an iterable and returns it in a form of enumerating object. So for every element in a, it makes a tuple (index, a[index]), where here: index will increase from 0 to 6.

Then for v, k in enumerate(a): we have already seen what enumerate(a) does, now you tell Python that for each loop, the tuple (index, a[index]) is represented by v, k. So v = index and k = a[index].

Then at last we find {k: v for v, k in enumerate(a)}, the accolades tell that you're making a dictionary. The k: v tells you that every loop, you will take k as a key of your dictionary with v the corresponding value. So the dictionary its keys will exist out of the elements of a, with their corresponding value equaling their indexc in the list a.

Now you have to take in mind that in a dictionary, each key can only exist once. So when the program comes across a key that already exists in the dictionary, it will overwrite it. That is why for example the first '2' with index 1, doesn't show up in the dictionary. Because it gets first overwritten by the '2' with index 5, after which this key and its value get overwritten by the last '2' and its index 6.

CodePudding user response:

#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.
  • Related