我有一个从数据库中读取的键值对字典:一个字符串字段和一个数字字段。字符串字段是唯一的,所以它是字典的键。
我可以按照键排序,但是如何基于值排序呢?
注意:我已经在Stack Overflow上阅读了这里的问题:How do I sort a list of dictionaries by a value of the dictionary?,并且可能可以更改我的代码以使用字典列表,但由于我实际上不需要字典列表,我想知道是否有更简单的解决方案来升序或降序排序。
我有一个从数据库中读取的键值对字典:一个字符串字段和一个数字字段。字符串字段是唯一的,所以它是字典的键。
我可以按照键排序,但是如何基于值排序呢?
注意:我已经在Stack Overflow上阅读了这里的问题:How do I sort a list of dictionaries by a value of the dictionary?,并且可能可以更改我的代码以使用字典列表,但由于我实际上不需要字典列表,我想知道是否有更简单的解决方案来升序或降序排序。
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
def returnminDict(_dct):
dict_items = _dct.items()
list_items = list(dict_items)
init_items = list_items[0]
for i in range(len(list_items)):
if list_items[i][1] > init_items[1]:
continue
else:
init_items = list_items[i]
return init_items
def SelectDictSort(_dct):
new_dict = {}
while _dct:
mindict = returnminDict(_dct)
new_dict.update(dict((mindict,)))
_dct.pop(mindict[0])
return new_dict
我尝试使用SelectDictSort({2: 5, 5: 1, 4: 3, 1: 1, 0: 1, 9: 2, 8: 2})
。它将返回:
{0: 1, 1: 1, 5: 1, 8: 2, 9: 2, 4: 3, 2: 5}
嗯...我不知道哪个是正确的,但这是我尝试过的...
x = {"b":4, "a":3, "c":1}
for i in sorted(x.values()):
print(list(x.keys())[list(x.values()).index(i)])
该方法不使用lambda,并可在Python 3.6上正常工作:
# sort dictionary by value
d = {'a1': 'fsdfds', 'g5': 'aa3432ff', 'ca':'zz23432'}
def getkeybyvalue(d,i):
for k, v in d.items():
if v == i:
return (k)
sortvaluelist = sorted(d.values())
# In >> Python 3.6+ << the INSERTION-ORDER of a dict is preserved. That is,
# when creating a NEW dictionary and filling it 'in sorted order',
# that order will be maintained.
sortresult ={}
for i1 in sortvaluelist:
key = getkeybyvalue(d,i1)
sortresult[key] = i1
print ('=====sort by value=====')
print (sortresult)
print ('=======================')