2016-12-05 70 views
0
dictionary = {(1,1):[(2,2),[(3,3),(4,4)],5]} 

dictionary[(2,2)] = [(3,3),[(4,4),(5,5)],6] 

dictionary[(3,3)] = [(4,4),[(5,5),(6,6)],7] 

print dictionary 

以上代碼給輸出:如何重新排列在Python詞典

{(3, 3): [(4, 4), [(5, 5), (6, 6)], 7], (1, 1): [(2, 2), [(3, 3), (4, 4)], 5], (2, 2): [(3, 3), [(4, 4), (5, 5)], 6]} 

但是,我想要的輸出順序輸入,即提供

{(1,1):[(2,2),[(3,3),(4,4)],5],(2,2):[(3,3),[(4,4),(5,5)],6],(3,3):[(4,4),[(5,5),(6,6)],7]} 

我如何重新安排詞典?

+0

而不是試圖做到這一點,看看有序字典https://docs.python.org/2/library /collections.html#collections.OrderedDict – elelias

+0

您是否需要訂購一般或僅在打印時訂購?當它打印時訂購 –

+0

.. –

回答

1

你需要使用一個有序字典,而不是正常的詞典是這樣的:

from collections import OrderedDict 

my_dict = OrderedDict() 

my_dict[(1,1)] = [(2,2), [(3,3), (4,4)], 5] 
my_dict[(2,2)] = [(3,3), [(4,4), (5,5)], 6] 
my_dict[(3,3)] = [(4,4), [(5,5), (6,6)], 7] 

print(my_dict) 
# Output: OrderedDict([((1, 1), [(2, 2), [(3, 3), (4, 4)], 5]), ((2, 2), [(3, 3), [(4, 4), (5, 5)], 6]), ((3, 3), [(4, 4), [(5, 5), (6, 6)], 7])]) 

print(my_dict[(1, 1)]) 
# Output: [(2, 2), [(3, 3), (4, 4)], 5]