在python中按值对字典排序

问题描述 投票:-2回答:2

这是我的字典:

d = {'jan': 50, 'feb': 30, 'march': 60, 'april': 50, 'may': 50, 'june': 60, 'july': 20}

我期待这样的输出:

d = {'jan': 50, 'april': 50, 'may': 50, 'march': 60, 'june': 60, 'feb': 30, 'july': 20}

当我运行这个程序时,我得到的输出不同于预期:

d = {'jan': 50, 'feb': 30, 'march': 60, 'april': 50, 'may': 50, 'june': 60, 'july': 20}
sortlist = sorted(d, key=d.get)
print(sortlist)
python sorting dictionary
2个回答
1
投票

您可以从collections.Counter计算每个值出现的次数开始:

from collections import Counter
c = Counter(d.values())
# Counter({20: 1, 30: 1, 50: 3, 60: 2})

现在对字典进行排序,查看每个值在key中使用sorted出现的次数:

sorted(d.items(), key=lambda x: c[x[1]], reverse=True)
[('jan', 50), ('april', 50), ('may', 50), ('march', 60), ('june', 60), 
 ('feb', 30), ('july', 20)]

但请注意,如果您从结果中获取字典,则不会保留订单,因为字典没有订单。

所以有一件事你可以使用collections.OrderedDict保持顺序,只需在结果列表中调用OrderedDict(res)


-1
投票
d={'january': 500, 'feb':600, 'march':300,'april':500,'may':500,'june':600,'july':200}

from collections import defaultdict
from collections import OrderedDict

count_dict = defaultdict(int)
for key, value in d.items():
  count_dict[value] += 1

首先,我们计算每个值的出现次数。可以用Counter代替defaultdict。然后根据我们刚刚创建的count_dict查找表对它们进行排序。

sorted_dict = OrderedDict(sorted(d.items(), key=lambda item: count_dict[item[1]], reverse=True))
print(sorted_dict)

>>> OrderedDict([('january', 500), ('april', 500), ('may', 500), ('feb', 600), ('june', 600), ('march', 300), ('july', 200)])

更新:您可以使用count_dict创建Counter,如:

from collections import Counter

count_dict = Counter(d.values())
© www.soinside.com 2019 - 2024. All rights reserved.