简体   繁体   English

如何对作为字典值的列表进行排序?

[英]How do I sort a list which is a value of dictionaries?

I need to sort a list which is a value of dictionaries by using a function with less computation cost.我需要使用计算成本较低的函数对作为字典值的列表进行排序。 I would not able to share the original code, so please help me with the following example.我无法共享原始代码,因此请帮助我使用以下示例。

I tried with the standard approach, I parsed the values, used the intermediate list to sort and stored it in the new dictionary which is highly computation intensive.我尝试使用标准方法,解析值,使用中间列表对其进行排序并将其存储在高度计算密集型的新字典中。 I am trying to streamline it, for that, I am expecting any suggestions or ways to incorporate.我正在尝试简化它,为此,我期待任何建议或合并方法。

Input输入

a= {'a':1, 'b': [2,8,4,3], 'c':['c',5,7,'a',6]} a= {'a':1, 'b': [2,8,4,3], 'c':['c',5,7,'a',6]}

Output输出

a= {'a':1, 'b': [2,3,4,8], 'c':['a','c',5,6,7]} a= {'a':1, 'b': [2,3,4,8], 'c':['a','c',5,6,7]}

You do not need to sort the dict, you need to sort all values that are lists inside your dict.您不需要对 dict 进行排序,您需要对 dict 中的所有列表值进行排序。 You do not need to create any new objects at all:您根本不需要创建任何新对象:

a= {'a':1, 'b': [2,8,4,3], 'c':['c',5,7,'a',6]} # changed c and a to be strings

for e in a:
    if isinstance(a[e],list):
        a[e].sort()         # inplace sort the lists

print(a)

Output:输出:

{'a': 1, 'c': [5, 6, 7, 'a', 'c'], 'b': [2, 3, 4, 8]}

This does not create new dicts nor does it create new lists - it simply sorts the list in-place.这不会创建新的字典,也不会创建新的列表——它只是对列表进行就地排序。 You can not get much faster/less computational then that unless you have special domainknowledge about your lists that would make programming a specialized in-place-sorter as replacement for list.sort() viable.除非您对列表具有特殊的领域知识,否则您无法获得更快/更少的计算量,这将使编程成为一个专门的就地排序器来替代 list.sort() 可行。


On Python 3 (thanks @Matthias Profil ) comparison between int ansd str give TypeError - you can "fix" that with some optional computation ( inspired by answers at: python-list-sort-query-when-list-contains-different-element-types ):在 Python 3 上(感谢 @Matthias Profil ) int ansd str 之间的比较给出了 TypeError - 您可以通过一些可选计算来“修复”它(受以下答案的启发: python-list-sort-query-when-list-contains-different-element -类型):

def IsString(item):    
    return isinstance(item,str)
def IsInt(item):
    return isinstance(item,int)

a= {'a':1, 'b': [2,8,4,3], 'c':['c',5,7,'a',6]} # changed c and a to be strings

for e in a:
    if isinstance(a[e],list):
        try:
            a[e].sort()         # inplace sort the lists
        except TypeError:
            str_list = sorted(filter(IsString,a[e]))
            int_list = sorted(filter(IsInt,a[e]))
            a[e] = int_list + str_list # default to numbers before strings

print(a)

In general (if your values are list of comparable items, eg numbers only), you could do something like this一般来说(如果您的值是可比较项目的列表,例如仅数字),您可以执行以下操作

sorted_dict = {key: sorted(value) for key, value in original_dict.items()}

If your values are single numbers/strings, you should change sorted(value) to sorted(value) if isinstance(value, list) else value .如果您的值是单个数字/字符串,您应该将sorted(value)更改为sorted(value) if isinstance(value, list) else value (thanks to user @DeepSpace for pointing out). (感谢用户@DeepSpace指出)。

However, the example you give in not valid, unless a and c refer to integer values.但是,您给出的示例无效,除非ac指的是整数值。

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

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