I have a tuple of objects that looks like this:
('MATE555', ([('Wdfd',7), ('dfs', 2), ('Tdfs77', 2), ('Fsf1', 1), ('s01', 1), ('Bdf1', 1), ('fs01', 1)],))and i want function created which would check if the name key exist.if it exist it would return the 2nd part of the tuple, if not it would return 'no key'. example
get_list('MATE555') would return [('Wdfd',7), ('dfs', 2), ('Tdfs77', 2), ('Fsf1', 1)开发者_运维技巧, ('s01', 1), ('Bdf1', 1), ('fs01', 1)]
and get_list("HIW6') would return 'no key'
Why are you using tuple object for 'key -> value' data model ? Python has a HashMap class called "Dictionary" which should be used instead of tuple for 'key -> value' data model as it offers more flexibility than tuple:
Creating dict from list:
your_dict = dict([(key1, value1), (key2, value2), (key3, value3), ...])
So in you case:
your_dict = dict([your_tuple])
Searching for key in dict:
if your_key in your_dict:
print your_dict[your_key]
else:
print "Key not present."
Adding new 'key -> value' pair:
your_dict[new_key] = new_value_object
Deleting 'key -> value' pair from dict:
del your_dict[key]
etc... More can be found here: http://docs.python.org/library/stdtypes.html#mapping-types-dict
if your_list[0] == 'MATE555':
print your_list[1]
else:
print 'no key'
Please read the Python tutorial first...this is really Python basics...
精彩评论