【问题标题】:How to sort a dictionary based on a list in python如何根据python中的列表对字典进行排序
【发布时间】:2014-03-13 11:45:24
【问题描述】:

我有一本字典

a = {'ground': obj1, 'floor 1': obj2, 'basement': obj3}

我有一个清单。

a_list = ['floor 1', 'ground', 'basement']

我想使用基于列表的键对字典 a 进行排序。有可能吗?

即:

sort(a).based_on(a_list) #this is wrong. But I want something like this. 

输出不必是另一个字典,我不介意将字典转换为元组然后对它们进行排序。

【问题讨论】:

    标签: python list sorting dictionary


    【解决方案1】:

    天真的方式,使用sorted() function 和自定义排序键(为dict.items()) 生成的每个(key, value) 对调用)对(键,值)元组列表进行排序:

    sorted(a.items(), key=lambda pair: a_list.index(pair[0]))
    

    更快的方法,先创建索引映射:

    index_map = {v: i for i, v in enumerate(a_list)}
    sorted(a.items(), key=lambda pair: index_map[pair[0]])
    

    这更快,因为index_map 中的字典查找需要 O(1) 恒定时间,而 a_list.index() 调用每次都必须扫描列表,因此需要 O(N) 线性时间。由于对字典中的每个键值对都调用了该扫描,因此朴素排序选项需要 O(N^2) 二次时间,而使用映射可以保持排序效率(O(N log N),线性时间)。

    两者都假定a_list 包含在a 中找到的所有 键。但是,如果是这种情况,那么您也可以反转查找并按顺序检索键

    [(key, a[key]) for key in a_list if key in a]
    

    这需要 O(N) 线性时间,并允许在 a_list 中使用 a 中不存在的额外键。

    明确地说:O(N) > O(N log N) > O(N^2),见this cheat sheet for reference

    演示:

    >>> a = {'ground': 'obj1', 'floor 1': 'obj2', 'basement': 'obj3'}
    >>> a_list = ('floor 1', 'ground', 'basement')
    >>> sorted(a.items(), key=lambda pair: a_list.index(pair[0]))
    [('floor 1', 'obj2'), ('ground', 'obj1'), ('basement', 'obj3')]
    >>> index_map = {v: i for i, v in enumerate(a_list)}
    >>> sorted(a.items(), key=lambda pair: index_map[pair[0]])
    [('floor 1', 'obj2'), ('ground', 'obj1'), ('basement', 'obj3')]
    >>> [(key, a[key]) for key in a_list if key in a]
    [('floor 1', 'obj2'), ('ground', 'obj1'), ('basement', 'obj3')]
    

    【讨论】:

    • @Martjin - 这解决了我的一个问题,但我在理解index_map[pair[0]] 中的pair 来自/派生时遇到了一些麻烦。它只能来自a.items() 元组,但它与pair 之间的联系尚不清楚。知道我在哪里可以找到详细的解释/更多关于这里发生的事情的例子吗?
    • @rong:正是dict.items()产生的(key, value)对。 sorted() 函数将每个被排序的元素传递给key 可调用对象,对于dict.items(),元素始终是具有两个对象(键和值)的元组。
    【解决方案2】:

    您可以按列表提供的键的顺序检索值,然后从键值对中创建一个新列表。

    例子:

    d = a      # dictionary containing key-value pairs that are to be ordered
    l = a_list # list of keys that represent the order for the dictionary
    # retrieve the values in order and build a list of ordered key-value pairs
    ordered_dict_items = [(k,d[k]) for k in l]
    

    【讨论】:

      猜你喜欢
      • 2018-09-27
      • 2023-03-26
      • 2021-12-29
      • 2014-07-13
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 2015-11-23
      相关资源
      最近更新 更多