在Python中的列表中排序嵌套的字典?

这个问题在这里已经有了答案:

  • 如何根据Python中字典的值对字典列表进行排序? 17个答案

  • data = [ { "PricingOptions": { "Price": 51540.72, "Agents": [ 4056270 ] } }, { "PricingOptions": { "Price": 227243.14, "Agents": [ 4056270],} } ]
    newlist = sorted(data, key=lambda k: k['PricingOptions']["Price"])
    print(newlist)
    

    输出:

    [{'PricingOptions': {'Price': 51540.72, 'Agents': [4056270]}}, {'PricingOptions': {'Price': 227243.14, 'Agents': [4056270]}}]
    

    按降序排列

    newlist = sorted(data, key=lambda k: k['PricingOptions']["Price"], reverse=True)
    print(newlist)
    #[{'PricingOptions': {'Price': 227243.14, 'Agents': [4056270]}}, {'PricingOptions': {'Price': 51540.72, 'Agents': [4056270]}}]
    

    您可以通过应用lambda表达式来使用sorted方法。

    sort_list = sorted(data, key=lambda elem: elem['PricingOptions']["Price"])
    

    产量

    [{'PricingOptions': {'Price': 51540.72, 'Agents': [4056270]}}, {'PricingOptions': {'Price': 227243.14, 'Agents': [4056270]}}]
    

    如果你想按降序对列表进行sort ,你只需要指定Truereverse属性。

    链接地址: http://www.djcxy.com/p/70779.html

    上一篇: Sort nested dictionary inside a list in Python?

    下一篇: Sorting a list of dictionaries by a specific dictionary key