Return Smallest Key in dictionary python
I need to find the smallest key in a dictionary with the following conditions:
- Returns the key with the nth smallest value.
- If the solution involves two keys that have the same value, return the the key that is lexicographically earliest.
- If n is larger than the number of distinct keys or equal to 0, then return null.
This is my solution (in return_smallest_key
) with test cases provided:
import math
def return_smallest_key(inputDict, n):
min_value = min(inputDict.values())
for val in inputDict:
if inputDict[val] == min_value:
if (min_value > len(inputDict.values())) or (len(inputDict.values()) ==0):
return None
return val
def printValue(n):
print('[', n, ']', sep='', end='')
test_case_number = 1
def check(expected, output):
global test_case_number
result = False
if expected == output:
result = True
rightTick = '\u2713'
wrongTick = '\u2717'
if result:
print(rightTick, 'Test #', test_case_number, sep='')
else:
print(wrongTick, 'Test #', test_case_number, ': Expected ', sep='', end='')
printValue(expected)
print(' Your output: ', end='')
printValue(output)
print()
test_case_number += 1
if __name__ == "__main__":
# Testcase 1
inputDict1 = {"laptop": 999,"smartphone": 999,"smart tv": 500,"smart watch": 300,"smart home": 9999999}
n1 = 2
expected_1 = "smart tv"
output_1 = return_smallest_key(inputDict1, n1)
check(expected_1, output_1)
# Testcase 2
inputDict2 = {"a": 10,"b": 20}
n2 = 0
expected_2 = None
output_2 = return_smallest_key(inputDict2, n2)
check(expected_2, output_2)
# Testcase 3
inputDict3 = {"a": 1,"b": 2,"c": 3,"d": 4,"e": 5}
n3 = 6
expected_3 = None
output_3 = return_smallest_key(inputDict3, n3)
check(expected_3, output_3)
# Testcase 4
inputDict4 = {"a": 10,"b": 20,"c": 3,"d": 2,"e": 9}
n4 = 1
expected_4 = "d"
output_4 = return_smallest_key(inputDict4, n4)
check(expected_4, output_4)
I'm not quite sure with the 2nd and 3rd requirements. I only passed test cases 2 and 4 so far.
As far as the current test data is concerned, you can first sort according to the value, and then take the index to get the corresponding value.
def return_smallest_key(inputDict, n):
if n == 0 or len(inputDict) < n:
return None
return sorted(inputDict, key=lambda x: inputDict[x])[n - 1]
Output:
✓Test #1
✓Test #2
✓Test #3
✓Test #4