This is homework, so I don't expect the answer, just a point in the right direction.
In python I have a dictionary that is like so:
{'bike101': ('Road Bike',
[('WH139', 2),
('TR102', 2),
('TU177', 2),
('FR101', 1),
('FB101', 1),
('BB101', 1),
('GS101', 1)]),
'bike201': ('Mountain Bike',
[('WH239', 2),
('TR202', 2),
('TU277', 2),
('FR201', 1),
('FB201', 1),
('BB201', 1),
('GS201', 1)]),
'bike301': ('Racing Bike',
[('WH339', 2),
('TR302', 2),
('TU377', 2),
('FR301', 1),
('FB301', 1),
('BB301', 1),
('GS301', 1)])}
For example 'Racing Bike' is the product name and the list of pairs is (part, amount required), respectively.
I have to write a function that, given the above dictionary and the product name as an argument will then return the key for it and return 'None' if the product name does not exist.
I used:
return [key for key, value in product_dict.iteritems() if list(value)[0] == string]
And this returned the correct key when tested but I don't know how to make it return 'none' if the product name doesn't exist and I am not sure if this is the best way to do this.'
I can only use the builtin functions in python, any help is greatly appreciated!
Since you're asking for hints, I won't post working code.
Your code is a list comprehension, so it outputs a list. If there is no result, the list will be empty. You can bind the list to a variable, use len()
to check its length and return None
if it is 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With