我是Python的新手,我想知道是否有一种更常见的方式来按字母顺序排序字典而不是我做的方式:
sorted_dictionary = sorted(dict.items(), key=lambda x: -x[1])
答案 0 :(得分:11)
reverse
可以使用sorted()
选项代替:
sorted(dict.items(), key=lambda kv: kv[1], reverse=True)
这会产生完全相同的输出,如果值不是数值,甚至可以工作。
答案 1 :(得分:3)
Python字典不可排序。您的undefined local variable or method `current_style' for #<#<Class:0x007f19b02bdda8>:0x007f19ba0c5ca8>
输出不是字典而是列表。您必须使用OrderedDict
sorted_dictionary
答案 2 :(得分:0)
根据值按升序对字典进行排序
d = {'a':5 , 'b':3 , 'd':1 , 'e':2 , 'f':4}
result = sorted(d.items() , key=lambda t : t[1])
for k,v in result:
print(k,v)
<强> RESULT 强>
d 1
e 2
b 3
f 4
a 5
# d.items=[('a', 5), ('b', 3), ('d', 1), ('e', 2), ('f', 4)]
# lambda t = ('a',5)
# lambda t : t[1] = 5
# result = [('d', 1), ('e', 2), ('b', 3), ('f', 4), ('a', 5)]
# k ,v = ('d',1)
# k = 'd'
# v = 1
根据降序排列字典
d = {'a':5 , 'b':3 , 'd':1 , 'e':2 , 'f':4}
result = sorted(d.items() , key=lambda t : t[1] , reverse=True)
for k,v in result:
print(k,v)
<强> RESULT 强>
a 5
f 4
b 3
e 2
d 1
# d.items=[('a', 5), ('b', 3), ('d', 1), ('e', 2), ('f', 4)]
# lambda t = ('a',5)
# lambda t : t[1] = 5
# result = [('a', 5), ('f', 4), ('b', 3), ('e', 2), ('d', 1)]
# k ,v = ('a',5)
# k = 'a'
# v = 5
答案 3 :(得分:0)
这应该有效
{k: v for k, v in sorted(dict.items(), key=lambda item: item[1], reverse = True)}
答案 4 :(得分:-1)
按python列表中值的降序排序:
items = {'a':6 , 'b':3 , 'c':1 , 'd':9}
sortedItems = sorted(items , key=items.get , reverse = True)
for element in sortedItems :
print (element, items.get(element))
输出是:
d 9
a 6
b 3
c 1
答案 5 :(得分:-1)
以下代码可以获取范围内所有数字的指数的所有素数因子
from sympy import primefactors
对于范围内的num(1,10001): k = num prime_factors = {}
for i in primefactors(num):
count = 0
while num % i == 0:
num = num/i
count += 1
prime_factors[i] = count
result = sorted(prime_factors.items() , key=lambda t : t[0] , reverse=True)
count = 1
num = k
print '\n%d can be broken down into the following prime factors:' % num,
print '\n%d = ' % num,
for k,v in result:
if count < len(result):
print '(%d ** %d) *' % (k,v),
count += 1
else:
print '(%d ** %d)' % (k,v)