2

What does this line of code do?

char_to_ix = { ch:i for i,ch in enumerate(sorted(chars)) }

What is the meaning of ch:i?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Hasani
  • 3,543
  • 14
  • 65
  • 125
  • 5
    It is `dict` comprehesion. Here https://www.python.org/dev/peps/pep-0274/ :) – han solo Feb 18 '19 at 15:41
  • 1
    char_to_ix will represent a dictionary containing item as key and their position as a value – vermanil Feb 18 '19 at 15:47
  • Does this answer your question? [Create a dictionary with comprehension](https://stackoverflow.com/questions/1747817/create-a-dictionary-with-comprehension) – Gino Mempin Jan 20 '23 at 14:43

2 Answers2

4

this is a dict comprehension as mentioned in by @han solo

the final product is a dict
it will sort your chars, attach a number in ascending order to them, and then use each character as the key to that numerical value here's an example:

chars = ['d', 'a', 'b']
sorted(chars) => ['a', 'b', 'd']
enumerate(sorted(chars)) => a generator object that unrolls into [(0, 'a'), (1, 'b'), (2, 'd')]
char_to_ix = {'a': 0, 'b': 1, 'd': 2}

Nullman
  • 4,179
  • 2
  • 14
  • 30
2

It is dict comprehension. ch - it is key in dictionary, i - value for that key.

Dictionary syntax is

dict = {
  key1: value1,
  key2: value2
}

With your code you will generate key: value pairs from enumerated chars. Key would be an element of sorted list of chars. Value - index of that element

Serg Kram
  • 31
  • 2