如果不对字典进行排序,为什么两个具有相同键名的字典按相同顺序返回值? [英] If dictionaries aren't ordered, why do two dictionaries with the same key names return values in the same order?

查看:119
本文介绍了如果不对字典进行排序,为什么两个具有相同键名的字典按相同顺序返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我用相同的键制作两个字典,即使它们没有顺序排列,它们似乎也以相同的顺序返回值。例如,如果我这样做:

If I make two dictionaries with the same keys, it seems like they return values in the same order, even though dictionaries aren't ordered. For instance, if I do this:

dict1 = {"a":1, "b":2, "c":3, "d":4}
dict2 = {"a":10, "b":20, "c":30, "d":40}

zip(dict1.values(), dict2.values())

它给出所需输出:

[(1, 10), (3, 30), (2, 20), (4, 40)]

为什么会这样?我可以总是指望两个具有相同键的字典,它们的值以相同的方式排序吗?

Why does this happen? Can I always count on two dictionaries with the same keys having their values ordered in the same way?

推荐答案

键通常位于相同的顺序,但没有保证。如果没有哈希值冲突,则键将按顺序排列。但是可能会发生冲突,在这种情况下,插入顺序会影响键的顺序。

Keys are often in the same order, but there is no guarantee. If there are no hash value collisions then the keys will be in order. But there can be collisions, and in that case the order of insertion will affect the order of the keys.

例如, 1 65 产生的哈希冲突是由于字典的大小是2的幂(至少在我的机器上)。 1%8 == 65%8 ,所以两个键映射到相同的哈希表存储桶。

For example, 1 and 65 generate hash collisions due to dictionaries having sizes that are powers of two (on my machine, at least). 1 % 8 == 65 % 8, so the two keys map to the same hash table bucket.

>>> {1: 'foo', 65: 'bar'}
{1: 'foo', 65: 'bar'}
>>> {65: 'bar', 1: 'foo'}
{65: 'bar', 1: 'foo'}

相同的词典,但是插入顺序不同意味着键的顺序不同。

Identical dictionaries but different insertion order means the keys are ordered differently.

>>> {1: 'foo', 65: 'bar'} == {65: 'bar', 1: 'foo'}
True

这只是在我的Python版本上起作用(不起作用)的一个示例。 Python语言未指定键如何映射到哈希存储桶。

This is just an example that happens to (not) work on my Python version. Python the language does not specify how keys map to hash buckets.

这篇关于如果不对字典进行排序,为什么两个具有相同键名的字典按相同顺序返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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