-1

I am a little confused about a piece of python code in using dict:

>>> S = "ababcbacadefegdehijhklij"
>>> lindex = {c: i for i, c in enumerate(S)}
>>> lindex
{'a': 8, 'c': 7, 'b': 5, 'e': 15, 'd': 14, 'g': 13, 'f': 11, 'i': 22, 'h': 19, 'k': 20, 'j': 23, 'l': 21}

How to understand it the "{c: i for i, c in enumerate(S)}" ? Could anyone give me some explanations?

2 Answers2

1

Bottom line, this creates a dictionary of the last occurence of each character in your string. Here is how...

enumerate

First enumerate returns an iterable which elements are a tuple of index and value.

Example

print(*enumerate(['a', 'b', 'c']))

Output

(0, 'a') (1, 'b') (2, 'c')

Since S is an iterable string, enumerate(S) return an iterator corresponding to...

(0, 'a') (1, 'b') (2, 'a') (3, 'b') (4, 'c') ...

Dictionary-comprehension

Second, this enumerate object is used by a dictionary-comprehension, which is a concise way to create a dictionary.

Example

d = { x: x + 1 for x in range(3) }

Output

{0: 1, 1: 2, 2: 3}

The dictionary-comprehension is used to create a dictionary where the keys are the letters in the string S and the items are the index of the characters.

Since a dictionary's key can only be associated to a single value, only the last value, i.e the last index at which the character occurs, is kept.

Equivalent code

Without enumerate and a dictionary comprehension, the code is equivalent to...

S = "ababcbacadefegdehijhklij"

lindex = {}

for i in range(len(lindex)):
    lindex[i] = S[i]
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
1

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.

Aeolus
  • 996
  • 1
  • 8
  • 22