2016-04-12 4 views
1

私は簡単な方法で、dictの文字列のようにrepr()を得ることができます。をキーでソートしました。dictのrepr()が注文しましたが、

my_print(dict(a=1, b=2, c=3)) -> "{'a': 1, 'b': 2, 'c': 3}" 

私のソリューション:

import collections 
print repr(collections.OrderedDict(sorted(dict(a=1, b=2, c=3).items()))) 

...は動作しません。ここで間違った出力:

OrderedDict([('a', 1), ('b', 2), ('c', 3)]) 

実装方法my_print()

print dict(a=1, b=2, c=3) 
+1

この出力は正確ですか? – deceze

+0

@deceze出力は**ソート**する必要があります。 repr(dict(..))はソートされません。 – guettli

+0

'dict'には順序がないので。 –

答えて

2

さて、あなたはJSONを使用することができます。dictsはPythonでソートされていないので、

これは解決策ではありません。

import json 
import collections 
def my_print(x): 
    return json.dumps(x) 

結果:

>>> my_print(collections.OrderedDict(sorted(dict(a=1, b=2, c=3).items()))) 
'{"a": 1, "b": 2, "c": 3}' 
+2

それではなぜ 'json.dumps(dict(a = 1、b = 2、c = 3)、sort_keys = True)'?その方法で入れ子にされた辞書も同様にキーソートされます... – bufh

1

JSONは単純なタイプのために動作します。手動でそのように行うことができます。

print '{' + ', '.join('%r: %r' % i for i in od.iteritems()) + '}' 

odcollections.OrderedDictオブジェクトです。

+1

''%r:%r'%i for od.iteritems()' ... – deceze

+0

@decezeそれを知らなかった。私は答えを更新します。ありがとう! –

1

のPython 3.7で標準辞書はgoing to be orderedで、あまりにもあなたのPython 3.6で、次はおそらく、Pythonの3.7で動作し、かつますので、CPythonの3.6で、dictは、ordered due to an implementation detailです:

について "間違っている" 何
def sorted_dict_repr(d): 
    return repr(dict(sorted(d.items()))) 
関連する問題