【问题标题】:Python, sorting a list of dicts with list in the valuePython,使用值中的列表对字典列表进行排序
【发布时间】:2021-07-12 22:24:13
【问题描述】:

我一直在尝试循环并排序包含字典的列表,其中包含值列表(SIDE_1 和 SIDE_2)。我想根据字典中每个列表的 0 索引进行排序。 EX:{'monday': [3, 2]},值 3 应该是排序标准。

我曾尝试使用 list sort() 方法,但我得到的最佳结果是两个 None 值(SIDE_1=None 然后 SIDE_2=None)。我也尝试过似乎更接近我的解决方案的 dict sorted() 方法,但是当我将 sorter() 函数作为键传递时,我总是得到 TypeError: string indices must be integers。

我已经通过打印测试了我的 sorter() 函数,并且我得到了我想要对我的列表进行排序的值,但是,当我尝试使用 sort() 或 sorted() 时,就会发生错误。

结果应该是:

SIDE_1: thursday, monday, wednesday, tuesday
SIDE_2: may, march, april, june

我的密码:

example = {'TOP': {'SIDE_1': [{'monday': [3, 2]}, {'tuesday': [1, 2]}, {'wednesday': [2, 1]}, {'thursday': [4, 0]}], 'SIDE_2': [{'march': [2, 1]}, {'april': [1, 2]}, {'may': [3, 3]}, {'june': [0, 3]}]}}


def sorter(obj):
    for o in obj:
        for h in o:
            return o[h][0] # when I use print to test what value I am getting it works correctly. however, i do get None at the end of each loop.

for top in example:
    for side in example[top]:
        x = example[top][side]
        print(sorted(x, key=sorter)) # if I just do print(sorter(x)) it returns the expected value(s)

结果:TypeError:字符串索引必须是整数。 --- 返回 o[h][0]

当我在 for 循环中打印(sorter(x)) 时,我得到: 3 1 2 4 没有 2 1 3 0 无

为什么我在每个循环结束时都得到 None?

【问题讨论】:

    标签: python sorting dictionary nested


    【解决方案1】:
    example = {
        "TOP": {
            "SIDE_1": [
                {"monday": [3, 2]},
                {"tuesday": [1, 2]},
                {"wednesday": [2, 1]},
                {"thursday": [4, 0]},
            ],
            "SIDE_2": [
                {"march": [2, 1]},
                {"april": [1, 2]},
                {"may": [3, 3]},
                {"june": [0, 3]},
            ],
        }
    }
    
    for k1, v1 in example.items():
        for k2, v2 in v1.items():
            v1[k2] = sorted(v2, key=lambda k: [*k.values()][0][0], reverse=True)
    
    # pretty print the output
    from pprint import pprint
    pprint(example)
    

    打印:

    {'TOP': {'SIDE_1': [{'thursday': [4, 0]},
                        {'monday': [3, 2]},
                        {'wednesday': [2, 1]},
                        {'tuesday': [1, 2]}],
             'SIDE_2': [{'may': [3, 3]},
                        {'march': [2, 1]},
                        {'april': [1, 2]},
                        {'june': [0, 3]}]}}
    

    【讨论】:

    • 非常感谢@Andrej 谢谢。你能简单解释一下 [*k.values()][0][0] 吗?
    • @CornellForeman 例如,对于k={'thursday': [4, 0]},[*k.values()][0][0] 获取第一个值(列表[4, 0]),然后是第一个元素(4)。 [*k.values()] 是 list(k.values()) 的同义词
    【解决方案2】:

    显然,它会报错。如果您在代码中添加 3 个打印语句 -

    
    
    def sorter(obj):
        for o in obj:
            for h in o:
                print(f'h is {h}')
                print(f'o is {o}')
                print(f'obj is {obj}')
                return o[h][0] 
    

    它会打印出来 -

    h is m
    o is monday
    obj is {'monday': [3, 2]}
    

    现在,您正在尝试返回 o[h][0] - 放置 h - o['m'][0] -> 这里的值 o 是星期一。你看到问题了吗?如果你做 o[0] 那么你会得到'm'。但是 o['m'][0] 会给你错误。

    我猜你想使用列表中的第一个元素作为键。如果你需要的话,这里是代码。

    def sorter(obj):
        for o in obj:
            return obj[o][0] # when I use print to test what value I am getting it works correctly. however, i do get None at the end of each loop.
    

    【讨论】:

    • obj 不是 {'monday': [3, 2]} 它是包含 {'monday': [3, 2]} dict 和 3 个其他 {. ..}的。 obj = 'SIDE_1' 或 'SIDE_2' 来自示例变量。
    • 它不是您的第二个函数中的列表,您从列表中获取 1 个元素并将该对象传递给函数排序器。 :)
    • 哦,好吧,您指的是 sorted() 如何查看我在 sorter() 中尝试执行的操作。谢谢。
    【解决方案3】:

    第一:

    def sorter(obj):
      for o in obj:        # o == 'monday'
        for h in o:        # h == 'm'
          return o[h][0]   # o[h][0] == 'monday'['m'][0]
    

    第二:

    print(sorter(x))    # this means 'obj' in sorter(obj) above receives [{'monday': ...
    

    这与 sorted 所做的不同,即:

    for value in x:    # sorted(x, key=sorter) calls your sorter() like this...
       sorter(value)   # ... and sorts based on the return values of those calls.
    

    我不知道你是如何得到无的。在 Python v3.9.2 中对我来说没有发生这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-11
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多