Reputation: 382
A computer store manages its laptop inventory by using Python dictionaries. Each dictionary entry has the string name of a specific computer laptop model as a key and its integer quantity in inventory as its corresponding value.
An example:
d = {"MS Surface":47, "HP Laptop Probook":144, "MacBook Pro":23, "Dell Laptop XPS": 10, "Asus Chromebook": 20}
Define a function low_inventory(laptop_dict, threshold) which returns a list of the names of all entries in laptop inventory laptop_dict whose quantities are less than (<) the int threshold.
Example: calling your function as total_items(d,47) should return :
['MacBook Pro', 'Dell Laptop XPS', 'Asus Chromebook']
def low_inventory(laptop_dict, threshold):
for akey in laptop_dict.keys():
if laptop_dict[akey] < threshold:
----
Could you please suggest how to do this. I am new to python and struggling with output.
Upvotes: 2
Views: 1002
Reputation: 6230
You can try filter
value = filter(lambda x: dict[x] < 3, keys)
And other iteration functions
http://book.pythontips.com/en/latest/map_filter.html
Upvotes: 1
Reputation: 92440
You need to return a list, so you could start by defining one. Something like:
low_inv = []
Then in your loop append()
the key (which is the name of the computer in this case) to that list if the inventory is low. Then return it:
d = {"MS Surface":47, "HP Laptop Probook":144, "MacBook Pro":23, "Dell Laptop XPS": 10, "Asus Chromebook": 20}
def total_items(laptop_dict, threshold):
low_inv = [] # new list
for akey in laptop_dict.keys():
if laptop_dict[akey] < threshold:
low_inv.append(akey) # append to it
return low_inv # return it
total_items(d,47)
#['MacBook Pro', 'Dell Laptop XPS', 'Asus Chromebook']
This can also be done as a list comprehension, which creates a list in one go without the explicit loop:
def total_items(laptop_dict, threshold):
return [akey for akey, inv in laptop_dict.items() if inv < threshold]
Upvotes: 2
Reputation: 1653
You can use d.items()
to iterate over the dictionary given the key and value. Try something like this:
def low_inventory(laptop_dict, threshold):
low = []
for key, value in laptop_dict.items():
if value < threshold:
low.append(key)
return low
Upvotes: 2