簡體   English   中英

返回字典python中的最小鍵

[英]Return Smallest Key in dictionary python

我需要在具有以下條件的字典中找到最小的鍵:

  1. 返回具有第 n 個最小值的鍵。
  2. 如果解決方案涉及具有相同值的兩個鍵,則返回按字典順序最早的鍵。
  3. 如果 n 大於不同鍵的數量或等於 0,則返回 null。

這是我的解決方案(在return_smallest_key中),提供了測試用例:

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)

我不太確定第二個和第三個要求。 到目前為止,我只通過了測試用例 2 和 4。

就當前的測試數據而言,可以先按值排序,然后取索引,得到對應的值。

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]

輸出:

✓Test #1
✓Test #2
✓Test #3
✓Test #4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM