Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding an element of a list when the list is in a dictionary?

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!

like image 698
Sean Avatar asked Apr 03 '11 12:04

Sean


1 Answers

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.

like image 62
Alexander Gessler Avatar answered Sep 28 '22 04:09

Alexander Gessler