Python:按值对字典排序(相等值)
我有这本字典,我想按值排序Python:按值对字典排序(相等值),python,list,sorting,dictionary,python-3.6,Python,List,Sorting,Dictionary,Python 3.6,我有这本字典,我想按值排序 d = {3: '__init__', 5: 'other', 7: 'hey', 11: 'hey'} 预期产出: {3:'__init__', 7: 'hey', 11: 'hey' 5: 'other'} 我写了这个函数 def ordenar(dic): d = {} list_2 = list(dic.values()) list_1 = list(dic.keys())
d = {3: '__init__', 5: 'other', 7: 'hey', 11: 'hey'}
预期产出:
{3:'__init__', 7: 'hey', 11: 'hey' 5: 'other'}
我写了这个函数
def ordenar(dic):
d = {}
list_2 = list(dic.values())
list_1 = list(dic.keys())
list_3 = []
for i,j in zip(list_1,list_2):
list_3.append((i,j))
def quicksort(l):
if len(l) <= 1:
return l
else:
(less_eq, piv, greater) = partition(l)
less_eq = quicksort(less_eq)
greater = quicksort(greater)
return less_eq + [piv] + greater
def partition(l):
piv = l[0]
i = 1
less_eq = []
greater = []
while i < len(l):
current = l[i]
if current <= piv:
less_eq.append(current)
else:
greater.append(current)
i = i + 1
return (less_eq, piv, greater)
s = quicksort(list_3)
for i in s:
d[i[0]] = i[1]
return d
在没有模块的情况下如何修复它?你能帮我吗
编辑:
我想按值对字典进行排序。如果值相等,我想要的是值按它的键排序。有可能吗?字典是无序的(至少在3.6之前),而是对条目进行排序
d = {3: '__init__', 5: 'other', 7: 'hey ', 11: 'hey'}
print(sorted(d.items(),key=lambda item:(item[0].strip(),item[1])))
# output => [(3, '__init__'), (7, 'hey '), (11, 'hey'), (5, 'other')]
如果你真的想把它作为一个dict(因为我无法理解的原因),并且你正在使用3.6+,那么你可以从你的排序项目中创建一个新的dict
d2 = dict(sorted(d.items(),key=lambda item:item[1]))
*(注意,在3.6中,dicts维护顺序是一个实现细节,不是保证,而是3.7+语言规范的一部分)
您可以在早期的Python中使用collections.OrderedDict执行相同的操作
from collections import OrderedDict
d2 = OrderedDict(sorted(d.items(),key=lambda item:item[1]))
因为你不能使用内置排序,这里是一个冒泡排序为你。。。虽然我不明白让陌生人在互联网上为你写一个排序函数比仅仅使用python内置的排序函数要好多少
def my_bubble_sort(list_thing,key_fn):
# sort a list in place by a key fn
changed = True
while changed:
changed = False
for i in range(len(list_thing)-1):
if key_fn(list_thing[i]) > key_fn(list_thing[i+1]):
list_thing[i],list_thing[i+1] = list_thing[i+1],list_thing[i]
changed = True
d = {3: '__init__', 5: 'other', 7: 'hey ', 11: 'hey'}
d_list = d.items()
my_bubble_sort(d_list,lambda item:(item[1].strip(),item[0]))
print(d_list)
从词法上讲,
'hey'
在'hey'
之前。。。你也应该在你的问题中提到你不能使用排序。。。因为使用sorted是解决这个问题的正确方法,您正在比较current@Ryan,我想按值对字典进行排序。如果值相等,我想要的是值按它的键排序。它可能吗?不管输出是列表还是字典,重要的是顺序,在输出中,它出现在(7,'嘿')之前(11,'嘿'),我想要(7,'嘿')之前(11,'嘿)'hey'
在词法上小于'hey'
,因此您需要详细说明使'hey'
小于'hey'
的规则,以便我告诉您如何实现它。我假设您希望在比较之前去掉值中的空格,然后进行说明我知道你的规则是什么很抱歉我在写问题时犯了一些错误。那么有可能做我想做的事情吗?没有排序或集合?我看到了,但是没有排序或集合还有其他方法吗?
def my_bubble_sort(list_thing,key_fn):
# sort a list in place by a key fn
changed = True
while changed:
changed = False
for i in range(len(list_thing)-1):
if key_fn(list_thing[i]) > key_fn(list_thing[i+1]):
list_thing[i],list_thing[i+1] = list_thing[i+1],list_thing[i]
changed = True
d = {3: '__init__', 5: 'other', 7: 'hey ', 11: 'hey'}
d_list = d.items()
my_bubble_sort(d_list,lambda item:(item[1].strip(),item[0]))
print(d_list)