简体   繁体   English

python 的 dict.items() 是否总是返回相同的顺序?

[英]Does python's dict.items() always return the same order?

Is it guaranteed that python 2.X's built-in methods dict.items() and dict.iteritems() will always return items in the same order?是否保证 python 2.X 的内置方法dict.items()dict.iteritems()将始终以相同的顺序返回项目? Or are these methods non-deterministic?或者这些方法是不确定的?

Within a single run of a program, and provided a dict d is not mutated in between, then在程序的单次运行中,如果 dict d没有在两者之间发生突变,那么

d.items()
d.iteritems()
d.keys()
d.iterkeys()
d.values()
d.itervalues()

are all consistent with each, and each returns the same sequence each time.都与每个一致,并且每次都返回相同的序列。

But if you modify the dict, it may shrink or grow and rearrange itself internally, which can change the order.但是如果你修改 dict,它可能会缩小或增长并在内部重新排列,这可能会改变顺序。 Which will then remain the same until the next mutation.然后将保持不变,直到下一个突变。

EDIT: one exception, which is quite deliberate.编辑:一个例外,这是相当深思熟虑的。 If you merely replace the value associated with an existing key, the order will not change.如果您只是替换与现有键关联的值,则顺序不会改变。 So if k in d is True , d[k] = v is harmless.因此,如果k in dTrue ,则d[k] = v是无害的。 All bets are off if you add a new key, or delete a key, though.但是,如果您添加新密钥或删除密钥,则所有赌注都将关闭。

If you're interested, you are able to use Visual Code and add breakpoints at each point that you're interested and monitor the local variables for differences across code runs... whether through the same program flow or through a separate run.如果您感兴趣,您可以使用 Visual Code 并在您感兴趣的每个点添加断点,并监视局部变量以了解代码运行之间的差异……无论是通过相同的程序流还是通过单独的运行。 You are also able to add expression watches.您还可以添加表情监视。 This will allow you to confirm for yourself the behavior of dictionary methods including the dict.items() and dict.iteritems()这将允许您自己确认字典方法的行为,包括 dict.items() 和 dict.iteritems()

you need customize function like that:您需要这样的自定义功能:

d = {'a': 4, 'c': 1, 'b': 2, 'd': 3}
def sorteddict(d={}):
    return sorted(d.items(),key=lambda x: x[1])
print(sorteddict(d))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM