Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A shop keeps stock = {"apples": 12, "bananas": 7}. Show the number of apples, and the number of mangoes, which are not in the dictionary, without an error.
get(key, default) never gives a KeyError.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, compare your working with the solution.
stock["mangoes"] would stop with a KeyError. We use get with a default of 0:
stock.get("apples", 0) gives 12.stock.get("mangoes", 0) gives 0, because there is no such key.Log in to join the discussion.
Loading…