Python 中巢狀字典值的求和


有時我們需要對巢狀字典的值進行求和,因此在這個問題陳述中,我們需要使用 Python 找到巢狀字典值的總和。

理解問題

眼前的問題是找到巢狀字典中存在的數值的總和,並且我們必須使用 Python 實現程式碼。所以巢狀字典是指字典內部的字典。我們必須找到巢狀的值並將它們加起來作為結果。

所有巢狀字典值的求和

在這種方法中,我們將使用 for 迴圈新增巢狀字典中存在的所有值。

演算法

  • 步驟 1 − 定義名為 summation_values 的函式,並在該函式中,我們將傳遞名為 the_dictionary 的巢狀字典作為輸入。

  • 步驟 2 − 初始化 sum 變數,我們將在其中儲存巢狀字典中所有值的總和。

  • 步驟 3 − 將為巢狀字典中的所有鍵值對啟動一個迴圈。然後將啟動條件以驗證該值是否為數字,然後將該值新增到 sum 變數中。

  • 步驟 4 − 如果整數在巢狀字典中,則遞迴呼叫上面建立的函式並將返回值新增到 sum 中。

  • 步驟 5 − 透過返回 sum 的值來結束演算法。

示例

# Function to get the summation of values
def summation_values(the_dictionary):
   sum = 0
   for value in the_dictionary.values():
      if isinstance(value, int):
         sum += value
      elif isinstance(value, dict):
         sum += summation_values(value)
   return sum
# input nested dictionary
nested_dict = {
   'apple': 10,
   'banana': {
      'cucumber': 12,
      'pineapple': {
         'orange': 23,
         'mango': 14
      }
   },
   'guava': 16
}

# pass the input dictionary and call the function
output = summation_values(nested_dict)

# show the output
print("The summation of nested dictionary values:", output)

輸出

The summation of nested dictionary values: 75

複雜度

summation_values 函式的時間複雜度為 O(N),其中 N 是字典中鍵值對的數量。造成這種複雜度的原因是函式取決於輸入字典的大小。

具有相同鍵的巢狀字典值的求和

在這種方法中,我們將新增巢狀字典中具有相同鍵的值。

演算法

  • 步驟 1 − 將巢狀字典初始化為 the_nested_dict。

  • 步驟 2 − 然後我們將初始化空字典以儲存具有相同鍵的總和值。

  • 步驟 3 − 然後將為 the_nested_dict 的值啟動迴圈。

  • 步驟 4 − 在外部迴圈內部,我們將對子字典項啟動另一個內部迴圈。

  • 步驟 5 − 然後在內部迴圈中,當前項值將新增到 sum_values 字典中相應的鍵中。

  • 步驟 6 − 使用 print() 函式列印更新後的 sum_values 字典。

  • 步驟 7 − 程式執行完成。

示例

# Initialize the nested dictionary
the_nested_dict = {
   'apple' : {'red' : 4, 'yellow' : 5, 'green' : 8},
   'guava' : {'red' : 8, 'white' : 10},
   'banana' : {'yellow' : 19, 'green' : 10}
}

#Initialize the empty dictionary
sum_values = dict()
for subdict in the_nested_dict.values():
   for key, elem in subdict.items():
      sum_values[key] = elem + sum_values.get(key, 0)

#Show the summation of nested dictionary values with same key
print("The summation values : " + str(sum_values))

輸出

The summation values : {'red': 12, 'yellow': 24, 'green': 18, 'white': 10}

複雜度

如果 N 是主字典中鍵值對的數量,而 M 是巢狀字典中鍵值對的數量,則時間複雜度為 O(NM)。原因是我們正在為每個主字典迭代巢狀字典。

結論

到目前為止,我們已經看到了兩種解決此類問題的方法。首先,我們加上了巢狀字典中存在的所有值,其次,我們只加上了相同或相同的鍵值。

更新於: 2023年10月16日

571 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告