2015/09/13

[Python]dictionaryからstrに変換

少し前にdictionaryからquerystringに変換するエントリーを書きましたが、今度は、dictionaryからstrに変換する方法を調べました。

Convert a python dict to a string and back
を流し読みすると、jsonパッケージを使ってjson化してみてはという書き込みがあったので、試してみた。

>>> import json
>>> dict_test = {}
>>> dict_test["hoge"] = "dict 1"
>>> dict_test["foo"] = "dict 2"
>>> dict_test
{'foo': 'dict 2', 'hoge': 'dict 1'}
>>> json_str = json.dumps(dict_test)
>>> json_str
'{"foo": "dict 2", "hoge": "dict 1"}'
>>> type(json_str)
<type 'str'>
確かに、str型で変換することができましたー。

これ便利ー。

0 コメント:

コメントを投稿