'Dictionary comprehension from random word (Python)
How can I express this using dictionary comprehension in python? Is it even possible? Thank you.
#word = "anyword\n"
k, word_dict = 0, {}
for letter in word[:-1]:
word_dict[k] = letter
k += 1
Solution 1:[1]
word_dict = {i: word[i] for i in range(len(word) - 1)}
This iterates over all indexes but last of word and associates the index with the corresponding letter
Maybe its more elegant using enumerate
word_dict = {i: letter for i, letter in enumerate(word[:-1])}
This yields the same result
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | freshpasta |
