如何統計巢狀 Python 字典中的元素?


要統計巢狀字典中的元素,我們可以使用內建函式 len()。此外,我們還可以使用一個遞迴呼叫並計算任意深度巢狀字典中元素的函式。

統計字典中的元素

讓我們首先建立一個 Python 字典,並使用 len() 方法統計其值。在這裡,我們在字典中包含了 4 個鍵值對並顯示了它們。產品、型號、單位可用是字典的鍵。除了單位鍵之外,所有鍵都具有字串值 -

示例

# Creating a Dictionary myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" } # Displaying the Dictionary print(myprod) # Count print(len(myprod))

輸出

{'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'}
4

現在,我們將建立一個巢狀字典並統計其元素。

統計巢狀字典中的元素

為了統計巢狀字典中的元素,我們使用了 sum() 函式並在其中逐一計算字典值。最後,顯示計數 -

示例

# Creating a Nested Dictionary myprod = { "Product1" : { "Name":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" }, "Product2" : { "Name":"SmartTV", "Model": "LG", "Units": 70, "Available": "Yes" }, "Product3" : { "Name":"Laptop", "Model": "EEK", "Units": 90, "Available": "Yes" } } # Displaying the Nested Dictionary print("Nested Dictionary = \n",myprod) print("Count of elements in the Nested Dictionary = ",sum(len(v) for v in myprod.values()))

輸出

Nested Dictionary = 
 {'Product1': {'Name': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'}, 'Product2': {'Name': 'SmartTV', 'Model': 'LG', 'Units': 70, 'Available': 'Yes'}, 'Product3': {'Name': 'Laptop', 'Model': 'EEK', 'Units': 90, 'Available': 'Yes'}}
Count of elements in the Nested Dictionary =  12

統計任意深度巢狀字典中的元素

為了統計任意深度巢狀字典中的元素,我們建立了一個自定義 Python 函式並在其中使用了 for 迴圈。迴圈遞迴呼叫並計算字典的深度。最後,它返回長度 -

示例

# Creating a Nested Dictionary myprod = { "Product" : { "Name":"Mobile", "Model": { 'ModelName': 'Nord', 'ModelColor': 'Silver', 'ModelProcessor': 'Snapdragon' }, "Units": 120, "Available": "Yes" } } # Function to calculate the Dictionary elements def count(prod, c=0): for mykey in prod: if isinstance(prod[mykey], dict): # calls repeatedly c = count(prod[mykey], c + 1) else: c += 1 return c # Displaying the Nested Dictionary print("Nested Dictionary = \n",myprod) # Display the count of elements in the Nested Dictionary print("Count of the Nested Dictionary = ",count(myprod))

輸出

Nested Dictionary = 
 {'Product': {'Name': 'Mobile', 'Model': {'ModelName': 'Nord', 'ModelColor': 'Silver', 'ModelProcessor': 'Snapdragon'}, 'Units': 120, 'Available': 'Yes'}}
Count of the Nested Dictionary =  8

更新於: 2022年8月11日

17K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.