לדלג לתוכן

2.3 קומפרהנשין פתרון

רק A!

# Given a list of words, create a new list with words that start with the letter 'A' using list comprehension.
words = ["Hi", "my", "name", "is", "Amit", "and", "I'm", "a", "programmer"]

words_starts_with_a = [word for word in words if word.lower()[0] == "a"]

החלף אותי

# Given a dictionary, convert the keys and values using dict comprehension
dictionary = {
              1: "one",
              2: "two",
              3: "three",
             }
dictionary = {value: item for (item, value) in dictionary.items()}

# Bonus: this level can be done easily without dict comprehension too.
keys = dictionary.keys()
values = dictionary.values()
dictionary = dict(zip(values, keys))

מיזוג מילונים

# Create a dictionary by merging two dictionaries using zip, where keys are from one dictionary and values are from another.
first_dictionary = {
              1: "one",
              2: "two",
              3: "three",
             }

second_dictionary = {
              "one": 1,
              "two": 2,
              "three": 3,
             }

keys = first_dictionary.keys()
values = second_dictionary.values()
dictionary = dict(zip(keys, values))