我想獲得一個已排序的字典。但mydict
和orddict
之間的項目順序似乎沒有改變。字典和python中的ordereddict之間的區別
from collections import OrderedDict
mydict = {'a':1,'b':2,'c':3,'d':4}
orddict = OrderedDict(mydict)
print(mydict,orddict)
# print items in mydict:
print('mydict')
for k,v in mydict.items():
print(k,v)
print('ordereddict')
# print items in ordered dictionary
for k,v in orddict.items():
print(k,v)
# print the dictionary keys
# for key in mydict.keys():
# print(key)
# print the dictionary values
# for value in mydict.values():
# print(value)
當你構建一個* dict *時,這個順序是* not *存儲的。因此,從字典中創建OrderedDict的順序與創建* dict *的順序相同。 – Maroun