Pythonで辞書の長さを取得する

辞書の長さを計算するには、Python の組み込み len() メソッドを使用できます。 len() メソッドは、キーの数を返します。 Python辞書

Python 辞書 len() 構文

構文: len(辞書)

戻る: 文字列の長さを示す整数を返します。

Name:Steve Age:30 Designation:Programmer 

辞書の長さを求める基本的な例

Python3




dict1> => {> 'Name'> :> 'Steve'> ,> 'Age'> :> 30> ,> 'Designation'> :> 'Programmer'> }> print> (> 'Dictionary:'> , dict1)> print> (> 'Length of dictionary:'> ,> len> (dict1))>

出力:

Dictionary: {'Name': 'Steve', 'Age': 30, 'Designation': 'Programmer'} Length of dictionary: 3 

ネストされた辞書の長さを調べる

人物について次の詳細を考慮してください。

Name:Steve Age:30 Designation:Programmer address: Street:Brigade Road City:Bangalore Country:India 

ネストされた辞書の長さを検索しようとしたときの問題:

Python3




# A nested dictionary> dict2> => {> # outer dictionary> > 'Name'> :> 'Steve'> ,> > 'Age'> :> 30> ,> > 'Designation'> :> 'Programmer'> ,> > 'address'> : {> # inner dictionary> > 'Street'> :> 'Brigade Road'> ,> > 'City'> :> 'Bangalore'> ,> > 'Country'> :> 'India'> > }> }> print> (> 'len() method :'> ,> len> (dict2))> print> (> 'len() method with keys() :'> ,> len> (dict2.keys()))> print> (> 'len() method with values():'> ,> len> (dict2.values()))>

出力:
len() メソッドとkeys() : 4
len() メソッドとvalues(): 4

ここでは、どの方法を適用しても、出力として「4」のみが得られます。しかし、実際のエントリ数は「7」です。キーは、名前、年齢、役職、住所、番地、都市、国です。このメソッドは、キーの 1 つの値である外部辞書を単一の値とみなします。

この問題を解決するには、内側の辞書の長さを外側の辞書に明示的に追加する必要があります。以下のようにコーディングできます。

Python3




# A nested dictionary> dict2> => {> > 'Name'> :> 'Steve'> ,> > 'Age'> :> 30> ,> > 'Designation'> :> 'Programmer'> ,> > 'address'> :> > {> > 'Street'> :> 'Brigade Road'> ,> > 'City'> :> 'Bangalore'> ,> > 'Country'> :> 'India'> > }> > }> # total length = length of outer dict +> # length of inner dict> length> => len> (dict2)> +> len> (dict2[> 'address'> ])> print> (> 'The length of the nested dictionary is:'> , length)>

出力:

The length of the nested dictionary is: 7 

今では正常に動作します!!! しかし、内部辞書の長さを毎回追加するように明示的にプログラムすることは可能でしょうか? 内部辞書が何個あるかが事前に分からない場合はどうすればよいでしょうか?ここで、次の詳細を考慮してください。

Name: first name:Steve last name:Jobs Age:30 Designation:Programmer address: Street:Brigade Road City:Bangalore Country:India 

ここには 2 つの内部辞書があります。これは、内部辞書の長さを毎回明示的に追加する最適化された方法ではありません。 isinstance() と len() メソッドを組み合わせることで、この問題を解決できます。このアイデアは、まず辞書全体の長さを変数に格納することです。 (ここでは「長さ」と入力します) 。次に、辞書のすべての value() を反復処理し、それが dict のインスタンスであるかどうかを確認します。もし '真実' 次に、その内部辞書の長さが検出され、変数に追加されます。 長さ 。このようにして、ネストされた辞書の全長を見つけることができます。

例 1: for ループを使用して、ネストされた辞書の長さを動的に検索します。

値が再び辞書である辞書内にさらに多くのキーがある場合。次に、各キーの値の型を確認する必要があります。それが辞書の場合は、値に対して len() を使用し、その値を外側の辞書の長さに追加します。

Python3




# nested dictionary> dict2> => {> > 'Name'> :> > {> > 'first_name'> :> 'Steve'> ,> > 'Last_name'> :> 'Jobs'> > },> > 'Age'> :> 30> ,> > 'Designation'> :> 'Programmer'> ,> > 'address'> :> > {> > 'Street'> :> 'Rockins Road'> ,> > 'City'> :> 'Bangalore'> ,> > 'Country'> :> 'India'> > }> > }> # storing the outer dictionary length> length> => len> (dict2)> # iterating to find the length> # of all inner dictionaries> for> i> in> dict2.values():> > # checking whether the value is a dictionary> > if> isinstance> (i,> dict> ):> > length> +> => len> (i)> > print> (> 'The length of the dictionary is'> , length)>

出力:

The length of the dictionary is 9 

注記: このアプローチは、辞書のネストが 2 レベルまでしかない場合にのみ機能します。

以下のように辞書がさらに深くネストされている場合:

Name: first name:Steve last name:Jobs Age:30 Designation:Programmer address: Street: St_number:4 St_name:Brigade Road City:Bangalore Country:India 

例 2: 再帰を使用してネストされた辞書の長さを検索する:

ここでは、再帰関数 count_nested_len() を使用して各辞書の長さをカウントし、辞書のキーを反復処理し、値が辞書になるとすぐにその辞書を再利用します。

Python3




# nested dictionary> dict2> => {> > 'Name'> :> > {> > 'first_name'> :> 'Steve'> ,> > 'Last_name'> :> 'Jobs'> > },> > 'Age'> :> 30> ,> > 'Designation'> :> 'Programmer'> ,> > 'address'> :> > {> > 'Street'> :> > {> > 'st_number'> :> 4> ,> > 'st_name'> :> 'Rockins Road'> > },> > 'City'> :> 'Bangalore'> ,> > 'Country'> :> 'India'> > }> > }> # we use recursive function to count> # length of nested dictionaries> def> count_nested_len(d):> > length> => len> (d)> > for> key, value> in> d.items():> > if> isinstance> (value,> dict> ):> > length> +> => count_nested_len(value)> > return> length> print> (> 'Nested dictionary length:'> ,> > count_nested_len(dict2))>

出力:

Nested dictionary length: 11 

アプローチ 3 : 辞書内包表記の使用

Python3

# ネストされた辞書
dict2 ={
'名前':
{
「first_name」:「スティーブ」、
「姓」:「ジョブ」
}、
「年齢」:30、
「役職」:「プログラマ」、
'住所':
{
'通り':
{
「st_number」:4、
「st_name」:「ロッキンズ ロード」
}、
「都市」:「バンガロール」、
「国」:「インド」
}
}

# 辞書内包表記を使用してネストされた辞書の長さを見つける
length = len({k: k の v, dict2.items() の v})

print(辞書の長さは, length)
#このコードは Edula Vinay Kumar Reddy によって提供されています

方法 4: sum() 関数でジェネレータ式を使用する。

アプローチ:

ジェネレータ式を使用して 1 のシーケンスを作成します。各 1 は辞書内のキーに対応します。次に、 sum() 関数を使用して 1 を加算し、辞書の長さを求めます。

アルゴリズム:

1.辞書内の各キーに対して 1 のシーケンスを生成するジェネレーター式を作成します。
2. sum() 関数を使用して、シーケンス内の 1 を合計します。
3.辞書の長さを表す合計を返します。

Python3




dict1> => {> 'Name'> :> 'Steve'> ,> 'Age'> :> 30> ,> 'Designation'> :> 'Programmer'> }> length> => sum> (> 1> for> key> in> dict1)> print> (length)>

出力

3 

このアプローチの時間計算量は O(n) です。ここで、n は辞書内のキーの数です。

このアプローチの空間複雑さは O(1) です。