在使用lis颠倒顺序后用python重建字典

2024-09-30 10:41:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在这篇文章中做同样的事情reverse dictionary order。我不懂如何使用OrderedDict。我用反向列表中使用的dict()方法尝试了这段代码 但它给了我最初的字典。在

mydic = {'n1': 3, 'n2': 9}
ol = mydic.items()
ol.reverse()
print(ol)
dc = dict(ol)
print(dc)

结果我得到:

^{pr2}$

有没有办法在颠倒顺序后重建词典?在

提前谢谢


Tags: 方法代码列表dictionary字典orderdc事情
3条回答

您的方法的主要问题是原始dict不保证其键的任何特定顺序。虽然您可以获得mydic项的快照,颠倒顺序,并将结果存储到OrderedDict中,但其输出将是未定义的(因为输入是未定义的)。在

换言之,垃圾在垃圾堆里出来。在

如果从键值对的iterable开始,那么可以使用OrderedDict

In [18]: ol = [('n2', 9), ('n1', 3)]

In [19]: OrderedDict(reversed(ol))
Out[19]: OrderedDict([('n1', 3), ('n2', 9)])

常规的Python字典不保留任何顺序,因此重新排列键不会有任何用处。在

{cd1>说的很简单,那就是:

>>> from collections import OrderedDict
>>> 
>>> ol = [('n2', 9), ('n1', 3)]
>>> dc = OrderedDict(ol)
>>> dc
OrderedDict([('n2', 9), ('n1', 3)])

使用collections.OrderedDict

Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.

相关问题 更多 >

    热门问题