Easy: Warm-Ups · Problem 12 of 82

Price Lookup

EasyGenerators and IteratorsPython

A price list is given as lines like "apple=1.50". Write price_lookup(lines) that returns a dictionary from the item name to its price as a float.

  • Lines that have no =, or whose price is not a number, are skipped.
  • If an item appears more than once, the last price wins.
  • Spaces around the name and the price are ignored.

Understand the problem

Look at the building blocks.

What does "apple=1.50".partition("=") return?

  1. ["apple", "1.50"]
  2. ("apple", "=", "1.50")
  3. ("apple", "1.50")

partition always returns a tuple of three: the part before the separator, the separator, and the part after. If the separator is missing, you get (text, "", ""), which makes it easy to detect a bad line.

What does float("1.5x") do?

  1. Returns 1.5
  2. Raises ValueError
  3. Returns 0.0

float raises a ValueError when the text is not a number. To skip bad lines you need try / except ValueError (a comprehension cannot contain try, so a small helper function or a loop is needed).

Write the solution

Return the dictionary.

def price_lookup(lines):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

How do you tell a good line from a bad one, and where do you put the try / except?

Hint 2: the shape of the answer

A loop over the lines. Use partition("="). If the separator is empty, continue. Try float(price); on ValueError, continue. Otherwise prices[name.strip()] = value.

Reflect

Solution

def price_lookup(lines):
    prices = {}
    for line in lines:
        name, separator, price = line.partition("=")
        if not separator:
            continue
        try:
            prices[name.strip()] = float(price)
        except ValueError:
            continue
    return prices

Another way: a helper and a comprehension

def _parse(line):
    name, separator, price = line.partition("=")
    try:
        return (name.strip(), float(price)) if separator else None
    except ValueError:
        return None

def price_lookup(lines):
    return dict(pair for pair in map(_parse, lines) if pair)

What this tests: str.partition, try / except for bad data, continue, and the later-wins behaviour of dictionary assignment.

Why not a single comprehension? A comprehension cannot contain try. When the parsing can fail, put it into a small helper function that returns None on failure, and filter the None out. Never force everything into one line.

float ignores spaces (float(" 1.5 ") is 1.5), but names need strip().

Cost: O(n).

What an interviewer might ask next: How would you report the skipped lines? (Collect their numbers in a second list and return both: a pattern from the Errors chapter.)