dict.values()是否按有序顺序返回? [英] Does dict.values() returns in an ordered sequence?

查看:398
本文介绍了dict.values()是否按有序顺序返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

dict_mark = {'Wang': 'C', 'Li': 'B', 'Ma': 'A'}
s = ''
for c in dict_mark.values():
    s += c
print(s)

字典是无序的,为什么dict_mark.values()总是像'C' 'B' 'A'一样返回此值序列?

dictionary is unordered,so why does dict_mark.values() always return this value sequence like 'C' 'B' 'A'?

为什么不是'B' 'A' 'C''A' 'B' 'C'?

推荐答案

无序操作并不意味着不确定.

Unordered dos not mean not deterministic.

从python 2.x文档:

如果items(),keys(),values(),iteritems(),iterkeys()和 调用itervalues()时,不会对 字典,列表将直接对应.

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.

Python 3.x文档中:

键和值以任意顺序进行迭代,该顺序是非随机的,在Python实现中会有所不同,并且取决于字典的插入和删除的历史记录.

Keys and values are iterated over in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

因此,在修改字典之前,返回的序列始终是相同的.您只是无法对其中要排序的对象进行假设.

Thus, the sequence returned is always the same until you modify the dictionary. You just can't make assumptions on the objects being sorted in it.

看看此问题及其答案他们讨论了为什么要对python 3.6+字典中的命令进行排序(以及如何进行排序).

Have a look at this question and the answers to it where they discuss about why (and how) in python 3.6+ dicts are actually ordered.

这篇关于dict.values()是否按有序顺序返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆