我有这本字典,我想按值排序。
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: '__init__', 5: 'other', 7: 'hey', 11: 'hey'}
如何用模块修复它?你能帮帮我吗?
修改
我想按值排序字典。如果值相等,我想要的是值按键排序。它可以吗?
答案 0 :(得分:0)
词典是无序的(至少在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')]
如果你真的想要它作为一个词典(由于我无法理解的原因)并且你使用3.6+然后你可以从你的分类项目中创建一个新的词典
d2 = dict(sorted(d.items(),key=lambda item:item[1]))
*(请注意,在3.6中,dicts维护顺序是一个实现细节,不是保证,但3.7+是语言规范的一部分)
你可以使用collections.OrderedDict
在早期的pythons中做同样的事情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)