2016-11-09 69 views
0

例詞典:如何按順序將列表添加到字典?

dictionary = {} 
dictionary['a'] = 1 
dictionary['b'] = 2 
dictionary['c'] = 3 
dictionary['d'] = 4 
dictionary['e'] = 5 
print(dictionary) 

運行這段代碼第1次:

{'c': 3, 'd': 4, 'e': 5, 'a': 1, 'b': 2} 

第二:

{'e': 5, 'a': 1, 'b': 2, 'd': 4, 'c': 3} 

3:

{'d': 4, 'a': 1, 'b': 2, 'e': 5, 'c': 3} 

我的EXP ected結果:

{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} 

,或者如果我的代碼是:

dictionary = {} 
dictionary['r'] = 150 
dictionary['j'] = 240 
dictionary['k'] = 98 
dictionary['l'] = 42 
dictionary['m'] = 57 
print(dictionary) 
#The result should be 
{'r': 150, 'j': 240, 'k': 98, 'l': 42, 'm': 57} 

因爲我的項目有100只++列出了字典將寫入一個文件,它會更容易閱讀。

P.S.對不起我的英語,如果我的問題標題不清楚。

謝謝。

回答

3

Python的dict本質上是無序的。爲了維護元素的插入順序,請使用collection.OrderedDict()

樣品試驗:

>>> import json 

>>> json.dumps(dictionary) # returns JSON string 
'{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}' 

按照

collections.OrderedDict() document

>>> from collections import OrderedDict 

>>> dictionary = OrderedDict() 
>>> dictionary['a'] = 1 
>>> dictionary['b'] = 2 
>>> dictionary['c'] = 3 
>>> dictionary['d'] = 4 
>>> dictionary['e'] = 5 

# first print 
>>> print(dictionary) 
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]) 

# second print, same result 
>>> print(dictionary) 
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]) 

爲它編寫的JSON文件,您可以使用json.dumps()作爲轉儲字典對象string

返回一個字典子類的實例,支持通常的字典方法。 OrderedDict是一個字典,它記住了鍵被首次插入的順序。如果新條目覆蓋現有條目,則原始插入位置保持不變。刪除一個條目並重新插入它將會把它移到最後。

+0

但是如果他想在最後打印文件,你不認爲它不會很有用,因爲它是一個對象而不是一個對話字典,當打印到文件時會打印出** JSON **結構。 – harshil9968

+1

@ harshil9968:在這種情況下,使用'json.dumps()'。更新了答案 –