我有一個整數作爲鍵的字典。請告訴我,使用排序的鍵是否存儲字典數據?應該按照公司的順序存儲密鑰?
我寫一些代碼來測試(如下):
>>>
>>> d = {1: 'a', 3: 'a'}
>>> d
{1: 'a', 3: 'a'}
>>> d[2] = 'a'
>>> d
{1: 'a', 2: 'a', 3: 'a'}
>>>
但我不知道這種行爲是標準和作品所有的時間。
我有一個整數作爲鍵的字典。請告訴我,使用排序的鍵是否存儲字典數據?應該按照公司的順序存儲密鑰?
我寫一些代碼來測試(如下):
>>>
>>> d = {1: 'a', 3: 'a'}
>>> d
{1: 'a', 3: 'a'}
>>> d[2] = 'a'
>>> d
{1: 'a', 2: 'a', 3: 'a'}
>>>
但我不知道這種行爲是標準和作品所有的時間。
python中的字典未排序。瞭解更多關於類型的字典在這裏: http://docs.python.org/library/stdtypes.html?highlight=dict#dict
但是你可以用sorted python built-in method到按鍵排序:
for k in sorted(myDict):
myDict[k] # do something
或者看看這裏collections.OrderedDict implementation
你也可以混合排序方法和OrderedDict以後使用它(確定這隻會在你不會添加新項目的情況下出現 - 否則它只是更好地使用排序方法):
d = {1: 'a', 3: 'a'}
from collections import OrderedDict
sorted_d = OrderedDict((k, d[k]) for k in sorted(d))
只是爲了說明所有'OrderedDict'都跟蹤*鍵的順序*。與保存鍵*排序*非常不同。 – mhyfritz
謝謝@mhyfritz。 –
一點點運行實驗會很快向您展示他們是沒有排序:
>>> d = {1: 'a', 3: 'a', 8: 'a'}
>>> d
{8: 'a', 1: 'a', 3: 'a'}
但即使是實現有關。不要依賴訂單。
內部字典不保留鍵的排序順序。如果你想爲C python快速的C實現看看sorteddict,它包含在我CPython的ordereddict包中: http://anthon.home.xs4all.nl/Python/ordereddict/
任何人都知道sorteddict的純python實現? –
[Python:Element order in dictionary]的可能重複(http://stackoverflow.com/questions/5792190/python-element-order-in-dictionary) – Jacob