I'll break down the one line into several lines so it's easier to understand. The following code does the same thing as the one liner in your example:
S = "ababcbacadefegdehijhklij"
lindex = {}
for count, letter in enumerate(S):
lindex[letter] = count
print(lindex)
Output will be:
{0: 'a', 1: 'b', 2: 'a', 3: 'b', 4: 'c', 5: 'b', 6: 'a', 7: 'c', 8: 'a', 9: 'd', 10: 'e', 11: 'f', 12: 'e', 13: 'g', 14: 'd', 15: 'e', 16: 'h', 17: 'i', 18: 'j', 19: 'h', 20: 'k', 21: 'l', 22: 'i', 23: 'j'}
(important to note dictionaries values are displayed randomly because order doesn't matter.)
What enumerate is doing is iterating through every letter in the string, but outputting both the letter and the count. So it will start with count = 0
, letter = "a"
, then count = 1
, letter = "b"
and so on. Then those values are added to the dictionary, lindex
with the key being the letter and the value being the count.
However, it is important to note that you can only have one of a key in a dictionary, so every time the same letter comes up, it's dictionary value is replaced.