Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 845
flybonzai Avatar asked Aug 18 '15 20:08

flybonzai


People also ask

How do you sort a dictionary in a tuple?

Method 1: Using sorted() method Using this method we can sort the dictionary of tuples based on keys, values, and items, we can use for loop to sort all elements in a dictionary of tuples.

Can you sort a dictionary based on keys?

Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.

How do you sort a tuple by key?

Given tuples, we need to sort them according to any given key. This can be done using sorted() function where we sort them using key=last and store last as the key index according to which we have to sort the given tuples.

Can you sort key values in dictionary Python?

Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse . Dictionaries are unordered data structures.


2 Answers

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, i.e. 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()))
like image 83
tobias_k Avatar answered Nov 09 '22 21:11

tobias_k


As @tobias_k has mentioned, sorted sorts tuples by its elements with decreasing priority, e.g. 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.

like image 25
Eli Korvigo Avatar answered Nov 09 '22 21:11

Eli Korvigo