tmori’s blog

公開メモ帳くらいの感覚で書いています。技術系多め。日常少なめ。

【Python】 str型からOrderedDict型に変換する方法

str型からOrderedDict型*1への変換についてまとめました。

1. JSONDecoderを使う場合

from collections import OrderedDict
import json

decoder = json.JSONDecoder(object_pairs_hook=OrderedDict)
json_string = '{"info":{"name":"牛タン", "price":380}}'
print(decoder.decode(json_string))

2. 文字列から直接デコードする場合

from collections import OrderedDict
import json

json_string = '{"info":{"name":"牛タン", "price":380}}'
od = json.loads(json_string, object_pairs_hook=OrderedDict)
print(od)

参考: python - Converting string to ordered dictionary? - Stack Overflow

*1:python 3.7からdict型が順序を保持するようになったらしいです。使い分けるべきなのかなぁ・・

参考: 普通の辞書とOrderedDictは何が違うのか?【Python 3.7】 | シラベルノート