Currently, I am studying one dictionary comprehensive notation of comprehension. Along the way, I tried to restore the dictionary comprehensive notation to the original long code and it succeeded, so I decided to leave it in the article.
In the first place, comprehensions allow you to compactly create Python data structures from one or more iterators. (Quote: Bill Lubanovic, translated by Yasuki Saito, translated by Takahiro Nagao, "Introduction to Python3", p.104 Publisher: O'Reilly Japan ISBN 978-4-87311-738-6)
Dictionary comprehension is one of the comprehensions, which is a dictionary format that uses keys and values.
First, I will write a comprehensive dictionary notation. Each character of the character string "python" is used as the key, and the index of each character is used as the value.
Dictionary comprehensive notation
word = "python"
letter_index = {letter:word.index(letter) for letter in word}
print(letter_count)
>> {"p": 0, "y": 1, "t": 2, "h": 3, "o": 4, "n": 5}
By using the inclusive notation such as the dictionary comprehensive notation in this way, you can write a dictionary of the character string of "python" in one line by turning the for loop. I think it will take some time to get used to it, but I'm sure it will be a lot easier to write code! (Perhaps)
Now, after practicing Python, I will return the dictionary comprehensive notation to its original form.
Return to the original shape
word = "python"
letter_index = {}
for letter in word:
letter_index[letter] = word.index(letter)
print(letter_count)
>> {"p": 0, "y": 1, "t": 2, "h": 3, "o": 4, "n": 5}
After all, when I made an empty dictionary and made a dictionary with letter_count using the for loop properly, the code became long. You can see that the dictionary comprehensive notation is useful.
But when I put it back in its original form, it became a Python practice and I'm glad I found a new practice method.
By Bill Lubanovic, Translated by Yasuki Saito, Translated by Takahiro Nagao, "Introduction to Python3" Publisher: O'Reilly Japan ISBN 978-4-87311-738-6
Recommended Posts