Python
 Computer >> コンピューター >  >> プログラミング >> Python

文字列辞書をPythonの辞書に変換する


この記事では、文字列を含む特定の辞書を、キーと値のペアの通常の辞書に変換する方法を説明します。

json.loadsを使用

json.loadsは指定された文字列を渡すことができ、データの構造を保持する通常の文字列として結果を提供します。したがって、指定された文字列ディクショナリをパラメータとしてこの関数に渡し、結果を取得します。

import json
stringA = '{"Mon" : 3, "Wed" : 5, "Fri" : 7}'
# Given string dictionary
print("Given string : \n",stringA)
# using json.loads()
res = json.loads(stringA)
# Result
print("The converted dictionary : \n",res)

出力

上記のコードを実行すると、次の結果が得られます-

Given string :
{"Mon" : 3, "Wed" : 5, "Fri" : 7}
The converted dictionary :
{'Mon': 3, 'Wed': 5, 'Fri': 7}

ast.literal_evalを使用

astモジュールからのこのメソッドは、上記のアプローチと同様に機能します。文字列を含む辞書は通常の値として解析され、通常の辞書を生成します。

import ast
stringA = '{"Mon" : 3, "Wed" : 5, "Fri" : 7}'
# Given string dictionary
print("Given string : \n",stringA)
# using json.loads()
res = ast.literal_eval(stringA)
# Result
print("The converted dictionary : \n",res)

出力

上記のコードを実行すると、次の結果が得られます-

Given string :
{"Mon" : 3, "Wed" : 5, "Fri" : 7}
The converted dictionary :
{'Fri': 7, 'Mon': 3, 'Wed': 5}

  1. 辞書の文字列表現をPythonの辞書に変換するにはどうすればよいですか?

    ここでast.literal_eval()を使用して、文字列をPython式として評価できます。式ノードまたはPython式を含む文字列を安全に評価します。提供される文字列またはノードは、次のPythonリテラル構造のみで構成されます:文字列、数値、タプル、リスト、dict、ブール値、およびなし。例: s = "{'baz' : 'lol', 'foo' : 'bar'}" import ast s = ast.literal_eval(s) print s['foo'], s['baz

  2. 与えられた辞書に従ってPython文字列を翻訳する方法は?

    オプションで、テーブル(文字列モジュールのmaketrans()関数で作成)を使用してすべての文字が翻訳された文字列のコピーを返すメソッドtranslate()を使用できます。文字列deletecharsで見つかったすべての文字を削除します。 例 from string import maketrans   # Required to call maketrans function. intab = "aeiou" outtab = "12345" trantab = maketrans(intab, outtab) str = "