简体   繁体   English

字典如何在python中添加键?

[英]How does the dictionary add keys in python?

When I run the code and change my range to 1, I get what I expect when I set the range to 2 I still get the first 2 sets I the right order once I tell it to adda third set they are no longer in order (the newest item added is not put at the end). 当我运行代码并将范围更改为1时,我得到了将范围设置为2时的期望值,一旦我告诉它添加了第三组它们就不再按顺序排列了,那么我仍然以正确的顺序获得了前2组(添加的最新项目未放在末尾)。 Why is this/what is the rule for determining where the newest item will be placed in a dictionary? 为什么使用此/什么规则来确定将最新项目放置在词典中的位置?

coded2 = []
for char in coded:
    coded2.append(char)

plain2 = []
for char in plain:
    plain2.append(char)

i = 0
d = {}

for num in range(5):
    d[coded2[i]] = plain2[i]
    i += 1
print d

In Python, dictionaries are unordered. 在Python中,字典是无序的。 The items are not stored in the order in which they are entered. 这些项目未按输入顺序存储。 You can use OrderedDict if you wish to conserve the order. 如果您希望保留订单,则可以使用OrderedDict

from collections import OrderedDict
d = OrderedDict()

for num in range(5):
    d[num] = num
print d #OrderedDict([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)])

In python dict is really a list with a hash function to generate indices. 在python中, dict实际上是一个具有哈希函数以生成索引的list

The hash function is exposed by python: 哈希函数由python公开:

>>> hash
<built-in function hash>

Note that the hash function was changed in python 3: 请注意,哈希函数在python 3中已更改:

Python2.7.10 Python2.7.10

>>>>>> hash("foo")
-740391237

Python3.5.0 的Python3.5.0

>>> hash("foo")
866150152168011056

When you type 当您键入

mydict = {}

What really happens is that python will allocate an empty list with size 8 . 真正发生的是python将分配一个大小为8空列表

When you now start adding items to the mydict python will calculate the hash values of the items and consider the 3 least significant bits thereof to calculate its index in the list: 当您现在开始向mydict添加项目时,python将计算项目的哈希值,并考虑其中的3个最低有效位以计算其在列表中的索引:

def bits(integer):
    return "".join(str(x) for x in [1&(integer>>i) for i in range(32)[::-1]])
>>>for item in "myitem","hashfunction","python":
       print(bits(hash(item))[-3:])
101
100
000

So a dict with these keys will have a different order than you expect: 因此,具有这些键的字典将具有与您期望的顺序不同的顺序:

>>> mydict={}
>>> mydict["myitem"]=None
>>> mydict["hashfunction"]=None
>>> mydict["python"]=None
>>> print mydict
{'python': None, 'hashfunction': None, 'myitem': None}

They're the order of the last three digits of the hash in the dict. 它们是字典中哈希的最后三位数字的顺序。

As the dict gets fuller, python will reallocate it and use a different hash, for small dictionaries ( up to 128k) it will quadruple its size , for larger dicts it will *double its size**. 随着字典变得更完整,python将重新分配它并使用其他哈希,对于小型字典(最大128k),它将增加四倍 ,对于较大的字典,它的大小将变成“两倍”。 This reallocation happens when the dict gets 2/3 full. 当dict占满2/3时会发生这种重新分配。

>>> keys=["myitem","hashfunction","python","in","a","super","large","dict"]
>>> for item in keys:
    print(item, bits(hash(item))[-5:])
('myitem', '01101')
('hashfunction', '00100')
('python', '01000')
('in', '10111')
('a', '00000')
('super', '11100')
('large', '10000')
('dict', '10100')
>>>mydict={key:None for key in keys}
>>>print mydict
{'a': None, 'hashfunction': None, 'python': None,
'myitem': None, 'large': None, 'dict': None, 'in': None, 'super': None}

This means that the order in a dict will change while you're putting in more items, sometimes radically. 这意味着,当您放入更多项目时, dict中的顺序将发生变化,有时会发生根本变化。

Note that a dict will only ever increase its size, never shrink as you del items from it. 请注意,字典只会增加其大小,而不会在您从中del项目时缩小。

To know more about dict and how it handles hash collisions I recommend Brandon Rhodes' excellent Pycon2010 talk on the inner workings of dict : The mighty dictionary 要了解有关dict及其如何处理哈希冲突的更多信息,我推荐Brandon Rhodes在dict的内部工作原理方面的出色 Pycon2010演讲: 强大的字典


Bottom line is that in a dict you should never rely on its order. 最重要的是,在dict您永远不应依赖其顺序。

Raymond Hettinger implemented an OrderedDict class in the collections module. Raymond Hettinger在collections模块中实现了OrderedDict类。

from collections import OrderedDict
d = OrderedDict()

for num in range(5):
    d[num] = num
print d #OrderedDict([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)])

It inherits from dict but wraps around some code to remember the order in which the keys were added. 它继承自dict但包装了一些代码以记住键的添加顺序。 You can rely on the ordering of OrderedDict . 您可以依赖OrderedDict的顺序。

Here you can use OrderDict 在这里您可以使用OrderDict

According to Link : 根据链接

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. 在有序字典上进行迭代时,将按照项的键首次添加的顺序返回项。

class collections.OrderedDict([items]) Return an instance of a dict subclass, supporting the usual dict methods. class collections.OrderedDict([items])返回一个dict子类的实例,支持常用的dict方法。 An OrderedDict is a dict that remembers the order that keys were first inserted. OrderedDict是可以记住首次插入键的顺序的字典。 If a new entry overwrites an existing entry, the original insertion position is left unchanged. 如果新条目覆盖了现有条目,则原始插入位置将保持不变。 Deleting an entry and reinserting it will move it to the end. 删除条目并重新插入将其移至末尾。

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

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