Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.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 将dict转换为有序dict_Python_Dictionary_Ordereddictionary - Fatal编程技术网

Python 将dict转换为有序dict

Python 将dict转换为有序dict,python,dictionary,ordereddictionary,Python,Dictionary,Ordereddictionary,我有一个哈希表和一个lambda来进行如下排序: h = {"hlllleleo": 9, "hello": 5, "fgfgggf" : 7, "abcdefgh": 8} lbda = lambda x : h[x] from collections import OrderedDict as od od({x:h[x] for x in sorted(h, key=lbda)}) #Outputs: OrderedDict([('abcdefgh', 8), ('hllllel

我有一个哈希表和一个lambda来进行如下排序:

 h = {"hlllleleo": 9, "hello": 5, "fgfgggf" : 7, "abcdefgh": 8}
 lbda = lambda x : h[x]
 from collections import OrderedDict as od
 od({x:h[x] for x in sorted(h, key=lbda)})
 #Outputs:
 OrderedDict([('abcdefgh', 8), ('hlllleleo', 9), ('fgfgggf', 7), 
 ('hello', 5)])
为什么有序的dict没有在构建时进行排序?如果我在sorted()上循环,它将被排序:

 for x in sorted(h, key=lbda):
   print x, h[x]

 # Outputs:
 hello 5
 fgfgggf 7
 abcdefgh 8
 hlllleleo 9

原因很简单。您可以按键对字典进行排序,并使用理解创建一个新字典。但是,当字典被创建并传递给
orderedict
构造函数进行创建时,它已经忘记了顺序

让我们将你的听写理解转换为列表理解:

In [413]: [(x, h[x]) for x in sorted(h, key=lambda x : h[x])]
Out[413]: [('hello', 5), ('fgfgggf', 7), ('abcdefgh', 8), ('hlllleleo', 9)]
现在,字典也是这样:

In [414]: {x : h[x] for x in sorted(h, key=lambda x : h[x])}
Out[414]: {'abcdefgh': 8, 'fgfgggf': 7, 'hello': 5, 'hlllleleo': 9}

正如您所看到的,您生成的词典在顺序方面与列表理解没有任何相似之处,因为生成的dict已经忘记了它的顺序。

谢谢,我只是在进一步使用它时得出了相同的结论。