简体   繁体   English

在Python中按内容对字典排序

[英]Sorting a dictionary by contents in Python

I have a library called WinP 我有一个名为WinP的库

WinP = {}

WinP has 119 Lists, labeled WinP[1], WinP[2], ... WinP[119]. WinP有119个列表,分别标记为WinP [1],WinP [2],... WinP [119]。 Each list has 1 number in it. 每个列表中都有1个数字。 I want to sort the lists by the number inside of each list. 我想按每个列表中的数字对列表进行排序。

Ideally I'd like to return a list of numbers like [45, 13, 110, 8, ... 50] representing the Lists in WinP arranged by the value inside 理想情况下,我想返回一个数字列表,例如[45、13、110、8,... 50],它们表示WinP中由内部值排列的列表

If you want a sorted list of all values you can itertools.chain the values: 如果您想要所有值的排序列表,可以itertools.chain值:

from itertools import chain

print(sorted(chain.from_iterable(WinP.values())))

If you want the keys sorted by the values, pass the key WinP.get to sorted which will sort the keys by value: 如果要按值对键进行排序,请将键WinP.get传递给sorted,它将按值对键进行排序:

print(sorted(WinP,key=WinP.get))
sorted(WinP, key=lambda k: WinP[k][0])

Dictionaries in Python can be treated as iterables of their keys. Python中的字典可以视为其键的可迭代项。 You can sort the keys based on the first element of their corresponding value, which are one-element lists. 您可以根据键的对应值的第一个元素(一个元素列表)对键进行排序。 This is just a general approach that would sort lists of any size with any number of elements based on a single one of those elements. 这只是一种通用方法,可以根据单个元素中的任意一个对具有任意数量的元素的任何大小的列表进行排序。

However, because lists are already sortable in lexicographic order, and because all dictionaries have a method called get , this can be shortened to the clever expression in Padraic Cunningham's answer. 但是,由于列表已经可以按字典顺序排序,并且由于所有词典都有一个名为get的方法,因此可以将其缩短为Padraic Cunningham回答中的巧妙表达。

sorted(WinP, key=WinP.get)

Demo: 演示:

>>> from random import randint
>>> WinP = dict(zip(range(1,10), ([randint(1,10)] for _ in range(1,10))))
>>> WinP
{1: [9], 2: [5], 3: [3], 4: [1], 5: [2], 6: [3], 7: [4], 8: [8], 9: [10]}
>>> sorted(WinP, key=lambda k: WinP[k][0])
[4, 5, 3, 6, 7, 2, 8, 1, 9]
>>> sorted(WinP, key=WinP.get)
[4, 5, 3, 6, 7, 2, 8, 1, 9]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM