辞書は重要なコンテナであり、日常のプログラミングや Web 開発のほぼすべてのコードで使用されます。 パイソン 。使用すればするほど、使いこなす必要性が高まるため、それらについて学ぶ必要があります。
Input: { 'testname' : 'akshat','test2name' : 'manjeet','test3name' : 'nikhil'} Output: {'testname': 'akshat', 'test2name': 'manjeet', 'test3name': 'nikhil'} Explanation: Input type is but the output type is> 辞書を文字列に変更するさまざまな方法を見てみましょう。
辞書オブジェクトを文字列に変換する 会話
この記事で説明する方法は次のとおりです。
モデムとルーターの違い
- 使用する json.dumps() 方法
- 使用する str() 関数
- 使用する 印刷方法
Python で辞書を文字列に変換する json.dumps() メソッドを使用する
ここでは、dump() メソッドを使用できます。 JSON ライブラリをインポートして、辞書のデータ型を文字列に変換します。以下のコードでは、最初に辞書 test1 を取得し、次に使用します。 json.ダンプ メソッドを作成し、その中に tes1 辞書を渡すと、必要な結果が得られます。 弦 フォーマット。
Python3
import> json> # initialising dictionary> test1>=> {>'testname'> :>'akshat'>,> >'test2name'> :>'manjeet'>,> >'test3name'> :>'nikhil'>}> # print original dictionary> print> (>type>(test1))> print> (>'initial dictionary = '>, test1)> # convert dictionary into string> result>=> json.dumps(test1)> # printing result as string> print> (>'
'>,>type>(result))> print> (>'final string = '>, result)> |
>
>
通信販売の横断
出力:
initial dictionary = {‘testname’: ‘akshat’, ‘test2name’: ‘manjeet’, ‘test3name’: ‘nikhil’} final string = {testname: akshat, test2name: manjeet, test3name: nikhil}> 空間の複雑さ : の上)
時間計算量 : の上)
str() 関数を使用した辞書から文字列への変換
の str() 関数は指定された値を文字列に変換します。 string 関数は、データ型を文字列型に変換するのにも役立ちます。このメソッドに辞書を渡すと、データ型が辞書から文字列データ型に変換されます。
Python3
int を文字列 Java に変換する
test1>=> {>'testname'> :>'akshat'>,> >'test2name'> :>'manjeet'>,> >'test3name'> :>'nikhil'>}> # print original dictionary> print> (>type>(test1))> print> (>'initial dictionary = '>, test1)> # convert dictionary into string> result>=> str>(test1)> # print resulting string> print> (>'
'>,>type>(result))> print> (>'final string = '>, result)> |
>
>
出力:
initial dictionary = {‘test2name’: ‘manjeet’, ‘testname’: ‘akshat’, ‘test3name’: ‘nikhil’} final string = {‘test2name’: ‘manjeet’, ‘testname’: ‘akshat’, ‘test3name’: ‘nikhil’}> 空間の複雑さ : の上)
時間計算量 : の上)
print メソッドを使用して辞書を文字列に変換する
辞書オブジェクトを文字列に変換する別の方法は、print を使用することです。 print は、任意の文字をきれいに印刷する方法を提供します。 パイソン という形式のデータ構造 印刷する インタプリタへの入力として使用できます。
以下は、print that モジュールを使用して辞書オブジェクトを文字列に変換する例です。
整数から文字列へ
Python3
マーキーHTML
import> pprint> # Initialize dictionary> d>=> {>'testname'> :>'akshat'>,>'test2name'> :>'manjeet'>,>'test3name'> :>'nikhil'> }> # Print original dictionary> print>(f>'Original dictionary: {d}'>)> # Convert dictionary into string using pprint.pformat()> result>=> pprint.pformat(d)> # Print resulting string> print>(f>'
Resulting string: {result}'>)> print>(>'Type is: '>,>type>(result))> |
>
>出力
Original dictionary: {'testname': 'akshat', 'test2name': 'manjeet', 'test3name': 'nikhil'} Resulting string: {'test2name': 'manjeet', 'test3name': 'nikhil', 'testname': 'akshat'} Type is: Space complexity : O(n) Time complexity : O(n) The print module provides more control over the formatting of the resulting string, such as indentation and line width, than the built-in str and json.dumps functions.>