1.List, dict and set comprehensions
AdvancedGiven words = ["apple", "Banana", "cherry", "date", "Elderberry", "fig"], build with comprehensions:
- a list of the words with more than 4 letters, in lower case
- a dictionary mapping each word to its length
- the sorted set of first letters, in lower case
Show hint
[expr for x in items if condition], {key: value for x in items} and {expr for x in items}.
Show solution
words = ["apple", "Banana", "cherry", "date", "Elderberry", "fig"]
long_words = [w.lower() for w in words if len(w) > 4]
lengths = {w: len(w) for w in words}
first_letters = sorted({w[0].lower() for w in words})
print(long_words)
print(lengths)
print(first_letters)['apple', 'banana', 'cherry', 'elderberry']
{'apple': 5, 'Banana': 6, 'cherry': 6, 'date': 4, 'Elderberry': 10, 'fig': 3}
['a', 'b', 'c', 'd', 'e', 'f']