Course 2.2Lesson 2 of 5
A dictionary comprehension writes key colon value then for, and a set comprehension uses curly brackets with one expression. Both can filter with if, and they build a dictionary or a set in one line. zip pairs the items of two lists, enumerate gives a position with each item, any is True if at least one item passes a test and all is True if every item passes, and for an empty collection any is False and all is True. sorted, min and max take a key function, which can be written as a short function with no name by using lambda. Use a named function when it is more than one short expression.
Try the code and the simulations beside the lesson.
After this lesson you can
zip and number items with enumerate,any and all about a collection, andlambda.The same idea works for other containers. Change the brackets, and the shape of the expression.
Predict first, then run it.
{key: value for item in iterable}. There is a colon between the key and the value. {word: len(word) for word in words} makes a dictionary of each word and its length.{expression for item in iterable}: curly brackets and one expression, with no colon. {word[0] for word in words} makes the set of first letters. The repeats disappear, because it is a set.if: {w: n for w, n in lengths.items() if n > 4} keeps the long words only.{n: w for w, n in d.items()} swaps keys and values. (If two keys have the same value, the later one wins.)Remember: {} alone is an empty dictionary. An empty set is set().
Four small tools do work that you would otherwise write as loops.
| Tool | What it does |
|---|---|
zip(a, b) | pairs the items of two lists: (a[0], b[0]), (a[1], b[1]), ... It stops at the shorter list. |
enumerate(items, start=1) | gives (position, item) pairs. |
any(test for item in items) | True if at least one item passes the test. |
all(test for item in items) | True if every item passes the test. |
zip is perfect for building a dictionary from two lists: {name: mark for name, mark in zip(names, marks)}, and for going through two lists together without positions.enumerate replaces for i in range(len(items)) when you need the position and the item.any([]) is False (nothing passes) and all([]) is True (nothing fails). This surprises people, but it is the sensible rule.any and all stop early: any stops at the first True, and all stops at the first False. You will see why this matters in the generator lessons.dict(zip(names, marks)) turns two matching lists into a dictionary in one line, as long as they are the same length.
You have used key=len and key=str.lower. The key function takes one item and returns what to compare. When no ready-made function fits, you write one.
def mark_of(pair):
return pair[1]
max(zip(names, marks), key=mark_of)For a very short function, Python has a shortcut: lambda. It is a function with no name, written in one expression: lambda pair: pair[1] means "a function that takes pair and returns pair[1]". It is used right where it is needed: max(zip(names, marks), key=lambda pair: pair[1]).
return word, no def.square = lambda n: n * n), but then a def is the better style.lambda can hold only one expression. If you need an if statement, a loop, or several lines, write a def.A rule of thumb: use a lambda for a one-line key, and a def for anything with a name that you will use again.
zip to give a list. It gives an iterator. Wrap it in list(...) to see it.zip of lists of different lengths. The extra items of the longer list are dropped without a warning.all([]) to be False. It is True.lambda. Use a def.any with a list comprehension any([...]) when a generator any(...) would stop early.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
{k: v for ...} is a dictionary. {e for ...} is a set. Both can filter with if.zip pairs two lists. enumerate gives a position with each item.any is True if one passes. all is True if all pass. For nothing: any is False, all is True.lambda x: expression is a short function with no name.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
{n: n * n for n in [1, 2, 3]} give?list(zip([1, 2, 3], ["a", "b"])) give?all([])?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.