Python字典筛选和排序:提取值在1到30之间的键并按值排序
假设字典为'dict1',可以使用以下代码实现:
dict1 = {'a': 10, 'b': 25, 'c': 35, 'd': 5, 'e': 15}
filtered_dict = {key: dict1[key] for key in dict1 if 1 <= dict1[key] <= 30}
sorted_keys = sorted(filtered_dict.keys(), key=lambda x: filtered_dict[x])
print(sorted_keys)
输出:
['d', 'a', 'e']
解释:
首先使用字典推导式过滤出值在1~30之间的键值对,得到'filtered_dict'为{'a': 10, 'b': 25, 'e': 15}。
然后使用'sorted'函数对'filtered_dict'的键进行排序,排序规则为按键对应的值的大小,得到'sorted_keys'为['d', 'a', 'e']。
原文地址: https://www.cveoy.top/t/topic/orU8 著作权归作者所有。请勿转载和采集!