Open in App
Not now

# Python – Sort Dictionary by key-value Summation

• Last Updated : 27 Feb, 2023

Given a Dictionary, sort by summation of key and value.

Input : test_dict = {3:5, 1:3, 4:6, 2:7, 8:1}
Output : {1: 3, 3: 5, 2: 7, 8: 1, 4: 6}
Explanation : 4 < 8 < 9 = 9 < 10 are increasing summation of keys and values.

Input : test_dict = {3:5, 1:3, 4:6, 2:7}
Output : {1: 3, 3: 5, 2: 7, 4: 6}
Explanation : 4 < 8 < 9 < 10 are increasing summation of keys and values.

Method 1: Using sorted() + lambda + items()

In this sort operation is performed using sorted(), lambda function is used to provide addition logic. The items() is used to get both keys and values.

## Python3

 `# Python3 code to demonstrate working of` `# Sort Dictionary by key-value Summation` `# Using sorted() + lambda + items()`   `# initializing dictionary` `test_dict ``=` `{``3``: ``5``, ``1``: ``3``, ``4``: ``6``, ``2``: ``7``, ``8``: ``1``}`   `# printing original dictionary` `print``(``"The original dictionary is : "` `+` `str``(test_dict))`   `# sorted() to sort, lambda provides key-value addition` `res ``=` `sorted``(test_dict.items(), key``=``lambda` `sub: sub[``0``] ``+` `sub[``1``])`   `# converting to dictionary` `res ``=` `{sub[``0``]: sub[``1``] ``for` `sub ``in` `res}`   `# printing result` `print``(``"The sorted result : "` `+` `str``(res))`

Output:

```The original dictionary is : {3: 5, 1: 3, 4: 6, 2: 7, 8: 1}
The sorted result : {1: 3, 3: 5, 2: 7, 8: 1, 4: 6}```

Method 2: Using dictionary comprehension and sorted()

Use dictionary comprehension to create a new dictionary with sorted key-value pairs. Sort the dictionary items using the lambda function which returns the sum of key-value pairs. Finally, use sorted() method to sort the dictionary items based on the lambda function result.

## Python3

 `# Python3 code to demonstrate working of` `# Sort Dictionary by key-value Summation` `# Using dictionary comprehension and sorted()`   `# initializing dictionary` `test_dict ``=` `{``3``: ``5``, ``1``: ``3``, ``4``: ``6``, ``2``: ``7``, ``8``: ``1``}`   `# printing original dictionary` `print``(``"The original dictionary is : "` `+` `str``(test_dict))`   `# sorting dictionary by key-value summation` `res ``=` `{k: v ``for` `k, v ``in` `sorted``(test_dict.items(), key``=``lambda` `x: x[``0``]``+``x[``1``])}`   `# printing result` `print``(``"The sorted result : "` `+` `str``(res))`

Output

```The original dictionary is : {3: 5, 1: 3, 4: 6, 2: 7, 8: 1}
The sorted result : {1: 3, 3: 5, 2: 7, 8: 1, 4: 6}```

Time complexity: O(n log n), where n is the number of items in the dictionary. This is because sorting the dictionary items takes O(n log n) time complexity.
Auxiliary space: O(n), where n is the number of items in the dictionary. This is because we create a new dictionary with the same number of items as the original dictionary.

My Personal Notes arrow_drop_up
Related Articles