2016-11-09 3 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} 

第三:

{'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あたり:

JSONファイルに書き込むために

>>> 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.dumps()を使用してstringへのdictオブジェクトをダンプすることができます

通常のdictメソッドをサポートするdictサブクラスのインスタンスを返します。 OrderedDictは、キーが最初に挿入された順序を記憶する辞書です。新しいエントリが既存のエントリを上書きする場合、元の挿入位置は変更されません。エントリを削除して再び挿入すると、最後まで移動します。

+0

しかし、もしそれを最後にファイルに出力したいのであれば、それはあまり有用ではないと思いませんか?** JSON **構造をプリントアウトするコンビネーション辞書ではありません。 – harshil9968

+1

@ harshil9968:その場合は、 'json.dumps()'を使います。更新された答え –

関連する問題