如何计算嵌套 Python 字典中的元素?
programmingpythonserver side programming
要计算嵌套字典中的元素,我们可以使用内置函数 len()。通过该函数,我们还可以使用递归调用并计算任意深度嵌套字典中的元素的函数。
计算字典中的元素
让我们首先创建一个 Python 字典并使用 len() 方法计算其值。在这里,我们在字典中包含了 4 个键值对并显示它们。Product、Model、Units 和 Available 是字典的键。除了 Units 键之外,所有键都具有字符串值 −
示例
# 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