简体   繁体   English

如何在键的第一个元素(元组)上对字典进行排序

[英]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. 我有一个字典,每个键都是一个值元组,我想使用sorted()方法对我的元组的第一个元素进行字典排序。 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 您只能将其项目排序为列表,或使用该列表来创建OrderedDict

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). 正如@tobias_k所提到的那样, sorted元素排序对元组sorted排序,优先级降低,例如,如果你取一个元组(a, b, c) ,最高的排序优先级转到a ,然后转到b等(默认sorted使用对象的比较方法和这是tuple比较的工作方式)。 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) ,但我相信你真的想留下这些值

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 . dict.items返回表单(key, value)元组,所以在这里你需要指定排序key

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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