【问题标题】:Sorting a dictionary of lists based on values of another dictionary根据另一个字典的值对列表字典进行排序
【发布时间】:2021-05-29 00:56:42
【问题描述】:

我有一个表格列表的字典:

dict1 = { key1 : ['a', 'b'], key2: ['c', 'd'], key3: ['e']}

我有另一本字典,格式为

dict2 = { a: 10, b: 11, c: 6, d: 15, e: 3}

我想根据 dict1 的值对 dict1 进行倒序排序,所以结果会是这样的:

sorted_dict = { key2:['d', 'c'], key1: ['b', 'a'], key3:['e']}

编辑:我需要保留键的顺序。我也可以将其转换为元组,这是完全可以接受的。

谢谢!

【问题讨论】:

  • 字典不是已排序的实体,因此即使您对其进行排序,它也会默认恢复为按字母顺序排序。如果您使用的是较新的 python 版本,则没有排序。
  • @thethiny 据我了解,他正在排序列表而不是字典键。
  • @TYZ 我也是这么想的,但是看看他的“sorted_dict”,他正在对字典的键进行排序。
  • @thethiny 我并没有真正找到 sorted_dict 中键的顺序的逻辑,所以我认为这并不重要。

标签: python sorting dictionary


【解决方案1】:

要对字典值进行排序,您可以这样做:

sorted_dict = {
    key: sorted(value, key=lambda x: dict2.get(x, 0), reverse=True)
    for key, value in dict1.items()
}

然后对字典进行排序(改变键的顺序)你可以这样做:

sorted_dict = dict(
    sorted(
        sorted_dict.items(),
        key=lambda x: sum(dict2.get(i, 0) for i in x[1]),
        reverse=True,
    )
)

关于dictionary 中键顺序的旁注。

字典保留插入顺序。请注意,更新密钥确实 不影响订单。删除后添加的键插入到 结束。

3.7 版更改:保证字典顺序是插入的 命令。这种行为是 CPython 3.6 的实现细节。

【讨论】:

    【解决方案2】:

    您可以在sorted 中使用key 参数:

    sorted_dict = {}
    
    for k in dict1:
        sorted_dict[k] = sorted(dict1[k], key=lambda v: dict2[v], reverse=True)
    

    这给出了:

    {'key1': ['b', 'a'], 'key2': ['d', 'c'], 'key3': ['e']}
    

    【讨论】:

    • 您不认为您需要根据dict1的总值而不只是1值进行排序吗? key=lambda x: sum([dict2[el] for el in dict1[x]])
    • 感谢您的回答,我添加了一个小修改,以保留键的顺序。我也想对键进行排序。
    • 我没有得到排序键的逻辑,也没有得到你之前基于总值排序的评论。如果您查看dict2 中的“a,b”和“c,d”之和,它们是相同的(都是 21)。
    【解决方案3】:

    您不能对字典进行排序,但可以对列表进行排序。我建议采用与我在下面所做的类似的方法,在映射 dict2 中的值后对键进行排序,然后从排序后的键创建一个新的 unordered 字典。

    dict1 = { "key1" : ['a', 'b'], "key2": ['c', 'd'], "key3": ['e']}
    dict2 = { "a": 10, "b": 11, "c": 6, "d": 15, "e": 3}
    sorted_keys = sorted([key for key in dict1], key=lambda x: sum([dict2[el] for el in dict1[x]]), reverse=True)
    sorted_dict = {k: dict1[k] for k in sorted_keys}
    

    这会产生

    {'key1': ['b', 'a'], 'key2': ['d', 'c'], 'key3': ['e']}
    

    按映射值排序

    【讨论】:

      猜你喜欢
      • 2022-11-14
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      相关资源
      最近更新 更多