我不知道這是一個有序字典要:
>>> k = "one two three four five".strip().split()
>>> v = "a b c d e".strip().split()
>>> k
['one', 'two', 'three', 'four', 'five']
>>> v
['a', 'b', 'c', 'd', 'e']
>>> dx = dict(zip(k, v))
>>> dx
{'four': 'd', 'three': 'c', 'five': 'e', 'two': 'b', 'one': 'a'}
>>> for itm in dx:
print(itm)
four
three
five
two
one
>>> # instantiate this data structure from OrderedDict class in the Collections module
>>> from Collections import OrderedDict
>>> dx = OrderedDict(zip(k, v))
>>> for itm in dx:
print(itm)
one
two
three
four
five
字典使用OrderdDict 保留原始的插入順序創建。換句話說,這樣的字典根據它們被插入的順序在鍵/值對上進行迭代。
因此,舉例來說,當你刪除密鑰,然後重新添加相同的密鑰,迭代順序變化:
>>> del dx['two']
>>> for itm in dx:
print(itm)
one
three
four
five
>>> dx['two'] = 'b'
>>> for itm in dx:
print(itm)
one
three
four
five
two
你可以使用按鍵額外的列表,以確定我在考慮的順序 – Nobody 2012-02-29 08:45:50
使用2個列表(python數組),然後使用「枚舉」,但這很複雜 – jondinham 2012-02-29 08:48:03
您是否還需要能夠通過密鑰快速訪問它? – 2012-02-29 08:50:44