【问题标题】:Creating new Dictionary to sort Key first and then sort on value创建新字典以首先对键进行排序,然后对值进行排序
【发布时间】:2020-05-09 16:56:52
【问题描述】:

我知道这是惯性排序的。我正在尝试制作一个新字典,按字母顺序对“键”进行排序,然后对元组中最后一个元素的值进行排序。

字典目前:

D1 = {'Lakers': [('James','PG',23,2), ('Davis', 'PF', 3, 3), ('Johnson', 'PG', 33, 
1)], 'Pistons': [('Billips', 'PG', 1, 1 ), ('Wallace', 'C', 3, 3)], 'Hawks': 
[('Young', 'PG', 11, 1), ('Collins', 'PF', 3, 2)] }

我想要的字典:

New_D1 = { 'Hawks':[('Collins', 'PF', 3, 2),('Young', 'PG', 11, 1)], 'Lakers': [('Davis', 'PF', 3, 3),('James','PG',23,2), ('Johnson', 'PG', 33, 1)], 'Pistons': [('Wallace', 'C', 3, 3),('Billips', 'PG', 1, 1 ) ] }

我当前的排序代码是:

New_D1  = dict(sorted(D1.items()))

这会创建一个新字典 (New_D1) 并且只对键进行排序。我现在需要对元组列表的最后一个元素中的值进行排序。

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    你可以在你已经在做的事情的基础上理解这一点:

    >>> {k: sorted(v, key=lambda t: -t[-1]) for k, v in sorted(D1.items())}
    {'Hawks': [('Collins', 'PF', 3, 2), ('Young', 'PG', 11, 1)], 'Lakers': [('Davis', 'PF', 3, 3), ('James', 'PG', 23, 2), ('Johnson', 'PG', 33, 1)], 'Pistons': [('Wallace', 'C', 3, 3), ('Billips', 'PG', 1, 1)]}
    

    【讨论】:

      【解决方案2】:

      您需要构建一个新的字典,通过对键进行排序进行插入,并添加同样排序的值

      result ={}
      for key, val in sorted(D1.items()):
          result[key] = sorted(val, key=lambda x: x[-1], reverse=True)
      

      您可以通过 dict-comprehension 内联修改,而不使用 tierce dict

      D1 = {key: sorted(val, key=lambda x: x[-1], reverse=True) for key, val in sorted(D1.items())}
      

      【讨论】:

        【解决方案3】:

        您可以使用itemgetter

        >>> from operator import itemgetter
        >>> {k:sorted(v, key=itemgetter(3)) for k,v in New_D1.items()}
        
        {'Hawks': [('Young', 'PG', 11, 1), ('Collins', 'PF', 3, 2)], 
        'Lakers': [('Johnson', 'PG', 33, 1), ('James', 'PG', 23, 2), ('Davis', 'PF', 3, 3)], 
        'Pistons': [('Billips', 'PG', 1, 1), ('Wallace', 'C', 3, 3)]}
        

        【讨论】:

          【解决方案4】:
          {k: sorted(v, key=lambda x: x[:-1]) for k,v in sorted(D1.items(), key=lambda x: x[0])}
          

          【讨论】:

            【解决方案5】:

            真的很简单,你甚至不需要上面提出的 lambda 函数:

            {k: sorted(v) for k,v in D1.items()}
            

            这会产生您正在寻找的结果:

            {'Lakers': [('Davis', 'PF', 3, 3),
              ('James', 'PG', 23, 2),
              ('Johnson', 'PG', 33, 1)],
             'Pistons': [('Billips', 'PG', 1, 1), ('Wallace', 'C', 3, 3)],
             'Hawks': [('Collins', 'PF', 3, 2), ('Young', 'PG', 11, 1)]}
            

            【讨论】:

              猜你喜欢
              • 2012-04-12
              • 2013-02-10
              • 1970-01-01
              • 1970-01-01
              • 2014-01-18
              • 2019-06-26
              相关资源
              最近更新 更多