python: sorting an ordered dictionary
问题 I create a dictionary: d[1] = {'a':1, 'b':2} d[2] = {'a':5, 'b':3} d[3] = {'a':3, 'b':2} I then try to sort by a field: d = collections.OrderedDict(sorted(d.items(), key=itemgetter(1))) so that I can output: for key in d: print key, d[key] This sorts on 'a', but I can't figure out how to sort on 'b'. How do I sort on 'b'? EDIT: I'm not sure how this is unclear. I'd like to sort so that the output is ordered by the values in field 'b'. 回答1: Modify your key function so that it explicitly