Using dictionary keys and values together
A workshop stores its product quantities in a dictionary named stock. Each key is a product name, and its value is the number of units available. The workshop wants at least target units of every product.
The function shortages(stock, target) identifies products that need restocking. It receives the current quantities in stock and the desired quantity per product in target. Its result must satisfy these rules:
- Include only products whose current quantity is below
target. Exclude products already at or above the target. - Use each product name as a key and the additional units needed as its value. For example,
shortages({"clips": 1}, 3)must return{"clips": 2}because two more clips are needed. - Return a new dictionary and leave
stockunchanged.
All quantities and the target are nonnegative integers. An empty stock produces {}. The order of entries does not affect the required result.
Listing 1 supplies three products and a target of 5. The required result is {"bolts": 3, "washers": 5}: bolts need three additional units, washers need five, and nuts are already at the target.
Compare the implementations in Listing 2. In each loop, name is intended to identify a product and qty its available quantity.
Which implementation satisfies all the requirements?
stock.items()is a dictionary method that takes no arguments. It returns a view that yields each(key, value)pair as a tuple when visited by a loop, without changing the dictionary. For example,{"red": 4, "blue": 7}.items()yields("red", 4)and("blue", 7); an empty dictionary yields no pairs. The view reflects changes to the dictionary, so keep its entries unchanged while this loop visits them.- In
for key, value in mapping.items():, unpacking assigns the first item of each pair tokeyand the second tovalue. For the pair("red", 4), these names receive"red"and4. Unpacking into two names requires a pair of two items.