如何按价值对字典进行排序?
我有一个从数据库中的两个字段中读取值的字典:一个字符串字段和一个数字字段。 字符串字段是唯一的,所以这是字典的关键。
我可以对键进行排序,但是如何根据这些值进行排序?
注意:我已阅读Stack Overflow问题如何按Python中字典的值对字典列表进行排序? 并可能可以改变我的代码有一个字典的列表,但因为我真的不需要一个字典的列表,我想知道是否有一个更简单的解决方案。
为了完整起见,我使用heapq发布了一个解决方案。 请注意,此方法适用于数字和非数字值
>>> x = {1: 2, 3: 4, 4:3, 2:1, 0:0}
>>> x_items = x.items()
>>> heapq.heapify(x_items)
>>> #To sort in reverse order
>>> heapq.nlargest(len(x_items),x_items, operator.itemgetter(1))
[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
>>> #To sort in ascending order
>>> heapq.nsmallest(len(x_items),x_items, operator.itemgetter(1))
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
months = {"January": 31, "February": 28, "March": 31, "April": 30, "May": 31,
"June": 30, "July": 31, "August": 31, "September": 30, "October": 31,
"November": 30, "December": 31}
def mykey(t):
""" Customize your sorting logic using this function. The parameter to
this function is a tuple. Comment/uncomment the return statements to test
different logics.
"""
return t[1] # sort by number of days in the month
#return t[1], t[0] # sort by number of days, then by month name
#return len(t[0]) # sort by length of month name
#return t[0][-1] # sort by last character of month name
# Since a dictionary can't be sorted by value, what you can do is to convert
# it into a list of tuples with tuple length 2.
# You can then do custom sorts by passing your own function to sorted().
months_as_list = sorted(months.items(), key=mykey, reverse=False)
for month in months_as_list:
print month
正如Dilettant指出的那样,Python 3.6现在可以保持顺序! 我想我会分享一个我写的函数,它简化了迭代(元组,列表,字典)的排序。 在后一种情况下,您可以对键或值进行排序,并且可以将数字比较考虑在内。 只有> = 3.6!
当你尝试使用一个持有例如字符串和int的iterable时,sorted()将会失败。 当然你可以用str()强制字符串比较。 但是,在某些情况下,您希望进行实际的数字比较,其中12
小于20
(字符串比较中不是这种情况)。 所以我想出了以下几点。 当你想要明确的数字比较时,你可以使用标志num_as_num
,它试图通过尝试将所有值转换为浮点数来进行明确的数字排序。 如果成功,它会进行数字排序,否则它会求助于字符串比较。
对改进或推送请求的意见表示欢迎。
def sort_iterable(iterable, sort_on=None, reverse=False, num_as_num=False):
def _sort(i):
# sort by 0 = keys, 1 values, None for lists and tuples
try:
if num_as_num:
if i is None:
_sorted = sorted(iterable, key=lambda v: float(v), reverse=reverse)
else:
_sorted = dict(sorted(iterable.items(), key=lambda v: float(v[i]), reverse=reverse))
else:
raise TypeError
except (TypeError, ValueError):
if i is None:
_sorted = sorted(iterable, key=lambda v: str(v), reverse=reverse)
else:
_sorted = dict(sorted(iterable.items(), key=lambda v: str(v[i]), reverse=reverse))
return _sorted
if isinstance(iterable, list):
sorted_list = _sort(None)
return sorted_list
elif isinstance(iterable, tuple):
sorted_list = tuple(_sort(None))
return sorted_list
elif isinstance(iterable, dict):
if sort_on == 'keys':
sorted_dict = _sort(0)
return sorted_dict
elif sort_on == 'values':
sorted_dict = _sort(1)
return sorted_dict
elif sort_on is not None:
raise ValueError(f"Unexpected value {sort_on} for sort_on. When sorting a dict, use key or values")
else:
raise TypeError(f"Unexpected type {type(iterable)} for iterable. Expected a list, tuple, or dict")
链接地址: http://www.djcxy.com/p/2987.html
上一篇: How do I sort a dictionary by value?
下一篇: Build an ASCII chart of the most commonly used words in a given text