[英]The order of keys in dictionaries
代碼:
d = {'a': 0, 'b': 1, 'c': 2}
l = d.keys()
print l
這將打印['a', 'c', 'b']
。 我不確定方法keys()
如何確定l 中關鍵字的順序。 但是,我希望能夠以“正確”的順序檢索關鍵字。 正確的順序當然會創建列表['a', 'b', 'c']
。
在 Python 3.7.0 中, dict
對象的插入順序保留特性已被聲明為 Python 語言規范的正式部分。 因此,您可以依賴它。
從 Python 3.6 開始,對於 Python 的 CPython 實現,字典默認維護插入順序。 不過,這被認為是一個實現細節; 如果您希望在其他 Python 實現中保證插入順序,您仍然應該使用collections.OrderedDict
。
當您需要記住插入項目順序的dict
,請使用collections.OrderedDict
類。
您可以使用OrderedDict (需要 Python 2.7)或更高版本。
另外,請注意OrderedDict({'a': 1, 'b':2, 'c':3})
將不起作用,因為您使用{...}
創建的dict
已經忘記了元素的順序。 相反,您想使用OrderedDict([('a', 1), ('b', 2), ('c', 3)])
。
如文檔中所述,對於低於 Python 2.7 的版本,您可以使用此秘籍。
來自http://docs.python.org/tutorial/datastructures.html :
“字典對象的 keys() 方法以任意順序返回字典中使用的所有鍵的列表(如果您希望對其進行排序,只需對其應用 sorted() 函數)。”
當你想使用它時,只需對列表進行排序。
l = sorted(d.keys())
盡管順序無關緊要,因為字典是 hashmap。 這取決於它被推入的順序:
s = 'abbc'
a = 'cbab'
def load_dict(s):
dict_tmp = {}
for ch in s:
if ch in dict_tmp.keys():
dict_tmp[ch]+=1
else:
dict_tmp[ch] = 1
return dict_tmp
dict_a = load_dict(a)
dict_s = load_dict(s)
print('for string %s, the keys are %s'%(s, dict_s.keys()))
print('for string %s, the keys are %s'%(a, dict_a.keys()))
輸出:
對於字符串 abbc,鍵是 dict_keys(['a', 'b', 'c'])
對於字符串 cbab,鍵是 dict_keys(['c', 'b', 'a'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.