logo

Python で辞書を作成する方法

辞書は Python の基本的なデータ構造であり、Python プログラマーにとって非常に重要です。これらはデータ値の順序のないコレクションであり、マップのようにデータ値を格納するために使用されます。 辞書 mutable、つまり変更できることを意味します。それらは次のような時間計算量を提供します。O(1)>メモリのオーバーヘッドと検索速度の効率に関して大幅に最適化されています。

リスト文字列Java

Python で辞書を作成する

パイソン 、curly 内に一連の要素を配置することで辞書を作成できます。 {} 中括弧は「カンマ」で区切ります。 Python で辞書を作成する方法をいくつかの例で見てみましょう。



項目を含むディクショナリを定義する

この例では、最初に空の辞書を宣言しました。 D の要素を追加しました。 Python リスト L 辞書に。各サブリストの最初の要素はキーで、2 番目の要素は値です。キーと値のペアを動的に保存します。

Python3








# Initialize an empty dictionary> D>=> {}> L>=> [[>'a'>,>1>], [>'b'>,>2>], [>'a'>,>3>], [>'c'>,>4>]]> # Loop to add key-value pair> # to dictionary> for> i>in> range>(>len>(L)):> ># If the key is already> ># present in dictionary> ># then append the value> ># to the list of values> >if> L[i][>0>]>in> D:> >D[L[i][>0>]].append(L[i][>1>])> > ># If the key is not present> ># in the dictionary then add> ># the key-value pair> >else>:> >D[L[i][>0>]]>=> []> >D[L[i][>0>]].append(L[i][>1>])> > print>(D)>

>

>

出力:

{'a': [1, 3], 'b': [2], 'c': [4]}>

キーと値の概要

この例では、Python の既存の辞書に別の要素を追加します。キーと値は別々に提供され、このペアを辞書に追加します。 my_dict

Python3

Java文字列を文字に変換




# Key to be added> key_ref>=> 'More Nested Things'> my_dict>=> {> >'Nested Things'>: [{>'name'>,>'thing one'>}, {>'name'>,>'thing two'>}]> }> # Value to be added> my_list_of_things>=> [{>'name'>,>'thing three'>}, {>'name'>,>'thing four'>}]> # try-except to take care of errors> # while adding key-value pair> try>:> >my_dict[key_ref].append(my_list_of_things)> > except> KeyError:> >my_dict>=> {>*>*>my_dict,>*>*>{key_ref: my_list_of_things}}> > print>(my_dict)>

>

Linuxの実行コマンド
>

出力:

{ 'Nested Things': [{'name', 'thing one'}, {'thing two', 'name'}], 'More Nested Things': [{'name', 'thing three'}, {'thing four', 'name'}] }>

Python の組み込み辞書関数メソッド

Python の辞書は、組み込み関数 dict() によっても作成できます。この例では、最初に中括弧 {} を使用して空の辞書を作成しました。次に、dict() メソッドを使用してリストを渡しました。

Python3




# Creating an empty Dictionary> Dict> => {}> my_list>=> [(>1>,>'Geeks'>), (>2>,>'For'>)]> print>(my_list)> # Creating a Dictionary> # with each item as a Pair> print>(>' Dictionary with the use of dict(): '>)> Dict> => dict>(my_list)> print>(>Dict>)>

>

ubuntu ビルドの必需品

>

出力:

[(1, 'Geeks'), (2, 'For')] Dictionary with the use of dict(): {1: 'Geeks', 2: 'For'}>