![](/img/trans.png)
[英]Is there a way to get corresponding values of indexes within keys in a dictionary?
[英]Get the keys corresponding to the 5 smallest values within a dictionary
如果我有一個 Python 字典,我如何獲取並返回與 5 個最小值對應的鍵?
給定輸入:
employees = {'any': 5, 'restraint': 8, 'shadow': 6, 'authority': 8, 'being': 6, 'now': 5, 'passed': 5, 'away': 5, 'they': 6, 'living': 6, 'together': 7}
檢查此解決方案:
employees = {'any': 5, 'restraint': 8, 'shadow': 6, 'authority': 8, 'being': 6, 'now': 5, 'passed': 5, 'away': 5, 'they': 6, 'living': 6, 'together': 7}
employees_list = [(k, v) for k, v in employees.items()]
employees_list.sort(key=lambda s: s[1])
keys = [i[0] for i in employees_list[:5]]
所以基本上發生了什么:
employees_list = [(k, v) for k, v in employees.items()]
將字典轉換為元組列表:
[('any', 5), ('restraint', 8), ('shadow', 6), ('authority', 8), ('being', 6), ('now', 5), ('passed', 5), ('away', 5), ('they', 6), ('living', 6), ('together', 7)]
然后根據第二個元素對列表元素進行排序:
employees_list.sort(key=lambda s: s[1])
結果:
[('any', 5), ('now', 5), ('passed', 5), ('away', 5), ('shadow', 6), ('being', 6), ('they', 6), ('living', 6), ('together', 7), ('restraint', 8), ('authority', 8)]
然后提取前 5 個鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.