Python 字典 len() 方法



Python 字典 len() 方法用於獲取字典的總長度。總長度表示字典中鍵值對的數量。

len() 方法返回字典中可迭代項的數量。在 Python 中,字典是鍵值對的集合。

語法

以下是 Python 字典 len() 方法的語法:

len(dict)

引數

  • dict - 需要計算長度的字典。

返回值

此方法返回字典的長度。

示例

以下示例演示了 Python 字典 len() 方法的使用。首先建立一個包含兩個鍵值對的字典 'dict'。然後使用 len() 方法獲取字典的長度。

# Creating a dictionary
dict = {'Name': 'Zara', 'Age': 7};
# printing the result
print ("Length : %d" % len (dict))

執行以上程式,輸出結果如下:

Length : 2

示例

在下面的程式碼中,建立了一個巢狀字典 'dict_1'。使用 len() 方法返回巢狀字典的長度。在這裡,該方法只考慮外部字典。因此,鍵 'Hobby' 的值被視為單個值。

# nested dictionary
dict_1 = {'Name' :'Rahul', 'RollNo':'43', 'Hobby':{'Outdoor' : 'Cricket', 'Indoor':'Piano'}}
res = len(dict_1)
print("The length of the dictionary is: ", res)

執行以上程式碼,輸出結果如下:

The length of the dictionary is:  3

示例

在這裡,我們顯式地將內部字典的總長度新增到外部字典中。

dict_1 = {'Name' :'Rahul', 'RollNo':'43', 'Hobby':{'Outdoor' : 'Cricket', 'Indoor':'Piano'}}
# calculating the length of the inner dictionary as well
l = len(dict_1) + len(dict_1['Hobby'])
print("The total length of the dictionary is: ", l)

以下為以上程式碼的輸出結果:

The total length of the dictionary is:  5

示例

如果我們有兩個或多個內部字典,以上示例不是正確的方法。正確的方法是將 isinstance() 方法與 len() 方法結合使用。isinstance() 方法用於檢查變數是否匹配指定的資料型別。

這裡我們首先將字典長度儲存在變數 'l' 中。然後我們遍歷字典的所有 values()。這將找出它是否是 dict 的例項。然後我們獲取內部字典的長度並將其新增到變數長度中。

dict_1 = {'Name' :'Rahul', 'RollNo':'43', 'Hobby':{'Outdoor' : 'Cricket', 'Indoor': 'Chesss'}, 'Activity1': {'Relax':'Sleep', 'Workout':'Skipping'}}
# Store the length of outer dict 
l = len(dict_1)
# iterating through the inner dictionary to find its length
for x in dict_1.values():
   # check whether the value is a dict
   if isinstance(x, dict):
      l += len(x)		
print("The total length of the dictionary is", l)

以上程式碼的輸出結果如下:

The total length of the dictionary is 8
python_dictionary.htm
廣告

© . All rights reserved.