简体   繁体   中英

How to sort dictionary on first element of the key (tuple)

I have a dictionary where each key is a tuple of values, I want to use the sorted() method to sort the dictionary on the very first element of my tuple. My code looks like this:

def mapData(header_list, dict_obj):
    master_dict = {}
    client_section_list = []
    for element in header_list:
        for row in dict_obj:
            if (row['PEOPLE_ID'], row['DON_DATE']) == element:
                client_section_list.append(row)
        element = list(element)
        element_list = [client_section_list[0]['DEDUCT_AMT'],
                    client_section_list[0]['ND_AMT'],
                    client_section_list[0]['DEDUCT_YTD'],
                    client_section_list[0]['NONDEDUCT_YTD']
                    ]
        try:
            element_list.append((float(client_section_list[0]['DEDUCT_YTD']) +
                                 float(client_section_list[0]['NONDEDUCT_YTD'])
                                 ))
        except ValueError:
            pass

    element.extend(element_list)
    element = tuple(element)
    master_dict[element] = client_section_list
    client_section_list = []
return sorted(master_dict, key=lambda key: key[master_dict[(1)]]

The last line is where I'm trying to find a way to sort it. My tuple looks like this:

(312178078,6/22/15,25,0,25,0,25.0)

Not entirely sure what you are trying to do, particularly what that function is supposed to return. I assume that you want to return the dictionary sorted by the first element in the key-tuples.

For this, there are two things to note:

  1. Tuples are by default sorted by their first element (and if those are the same, then by the second, and so on), so no special key function is required
  2. Regular dictionaries are unordered, ie they can not be permanently sorted in any order; you can only sort their items as a list, or use that list to create an OrderedDict instead

Some minimal example:

>>> d = {(2,4): 1, (1,3): 2, (1,2): 3, (3,1): 4}
>>> sorted(d)
[(1, 2), (1, 3), (2, 4), (3, 1)]
>>> sorted(d.items())
[((1, 2), 3), ((1, 3), 2), ((2, 4), 1), ((3, 1), 4)]
>>> collections.OrderedDict(sorted(d.items()))
OrderedDict([((1, 2), 3), ((1, 3), 2), ((2, 4), 1), ((3, 1), 4)])

In your case, you probably want this:

return collections.OrderedDict(sorted(master_dict.items()))

As @tobias_k has mentioned, sorted sorts tuples by its elements with decreasing priority, eg if you take a tuple (a, b, c) the highest sorting priority goes to a , then goes b etc (by default sorted uses object's comparison methods and this is how tuple comparison works). So sorted(master_dict) is all you need if you want a list of sorted keys, yet I believe you really want to leave the values

sorted(master_dict.items(), key=lambda key: key[0])

dict.items returns tuples of form (key, value) so here you need to specify the sorting key .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM