Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何先按值然后按键对词典排序_Python_Python 3.x_Sorting_Dictionary - Fatal编程技术网

Python 如何先按值然后按键对词典排序

Python 如何先按值然后按键对词典排序,python,python-3.x,sorting,dictionary,Python,Python 3.x,Sorting,Dictionary,我有一本字典 d={'g':1,'w':1,'h':3} 首先,我想先对值进行排序,然后按键进行排序,所以最终的输出应该如下所示 d={'h':3,'g':1,'w':1}从Python 3.6中,DICT是有序的,但为了确保需要使用集合模块中的有序DICT: from collections import OrderedDict d={'g':1,'w':1,'h':3} o = OrderedDict(sorted(((k, v) for k, v in d.items()), key=

我有一本字典

d={'g':1,'w':1,'h':3}

首先,我想先对值进行排序,然后按键进行排序,所以最终的输出应该如下所示


d={'h':3,'g':1,'w':1}

从Python 3.6中,DICT是有序的,但为了确保需要使用
集合
模块中的
有序DICT

from collections import OrderedDict

d={'g':1,'w':1,'h':3}

o = OrderedDict(sorted(((k, v) for k, v in d.items()), key=lambda v: (-v[1], v[0])))
print(o)
输出:

OrderedDict([('h', 3), ('g', 1), ('w', 1)])

使用Python 2,您可以通过自定义cmp函数实现这一点:

def compare(a,b):
  if a[1] < b[1]:
    return 1
  elif a[1] > b[1]:
    return -1
  else:
    if a[0] < b[0]:
      return -1
    elif a[0] > b[0]:
      return 1
    else:
      return 0

d={"h":3,"g":1,"w":1}
items = d.items()
items = sorted(items, cmp=compare)
print items
def比较(a,b):
如果a[1]b[1]:
返回-1
其他:
如果a[0]b[0]:
返回1
其他:
返回0
d={“h”:3,“g”:1,“w”:1}
items=d.items()
项目=已排序(项目,cmp=比较)
打印项目

如果您想对字典排序,那么最好使用python3.6或更高版本。
打印(已排序(d.items(),key=lambda x:x[1],reverse=True))
?您可以按->sortbyValue->sortbyKey或直接sortbyKey的步骤进行操作,它保持不变。你想通过中间步骤实现什么我想按值对字典排序,然后如果两个或更多键具有相同的值,我想根据键对它们进行排序。