What you are almost certainly looking for is to use the key= option for sorted(), which provides a function which returns an arbitrary sort key for each element. This function can check the type of its argument and take various actions. For instance:
import types
class obj(object):
def __init__(self, arg):
self.name = arg
def extract_name(obj):
if type(obj) is types.DictType:
return obj['name']
else:
return obj.__dict__['name']
d = { 'name': 'Jill'}
print sorted([obj('Jack'), d], key=extract_name)
More information can be found on the Python wiki
RichieHindle's suggestion of using isinstance is a good one. And while I was at it I thought it might be nice to support arbitrary element names instead of hardcoding 'name':
def extract_elem_v2(elem_name):
def key_extractor(obj):
dct = obj if isinstance(obj, dict) else obj.__dict__
return dct[elem_name]
return key_extractor
Which you can use like so:
print sorted(list_of_stuff, key=extract_elem_v2('name'))