简体   繁体   English

如何根据字典键对列表进行排序? Python

[英]How do you sort a list based on a dictionary key? Python

I have a dictionary我有一本字典

score={"basketball":[45,63],"baseball":[8,17],"football":[34,55],"soccer":[7,1]}

and a list和一份清单

sports=["football","basketball","baseball","soccer"]

Is their a way to sort my list to match my dictionary like so他们是一种对我的列表进行排序以匹配我的字典的方法吗

["basketball","baseball","football","soccer"]

You can convert the dictionary to a list of its keys and check a sport's index in this list:您可以将字典转换为其键列表并在此列表中检查运动的索引:

>>> sorted(sports, key=lambda sport: list(score).index(sport))
['basketball', 'baseball', 'football', 'soccer']

Dictionaries are ordered since Python 3.7 (also see https://stackoverflow.com/a/39980744/4354477 ).Python 3.7 开始订购字典(另请参阅https://stackoverflow.com/a/39980744/4354477 )。

Dictionaries are not ordered, so there is no ordering that will match the dictionary's ordering (it doesn't have one).字典没有排序,因此没有与字典的排序匹配的排序(它没有)。 You can observe this in the fact that two dictionaries specified with the same keys/values in different orders are considered equivalent:您可以观察到这样一个事实,即以不同顺序使用相同键/值指定的两个字典被认为是等效的:

Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> {'foo': True, 'bar': False} == {'bar': False, 'foo': True}
True

Given your example, the easiest fix would be to just initialize the list in the order you want to have it in, since these values are all hardcoded anyway.鉴于您的示例,最简单的解决方法是按照您想要的顺序初始化列表,因为这些值都是硬编码的。 In a more complex example, the solution might be to either use an OrderedDict or to use a dict combined with a list that maintains the ordering.在更复杂的示例中,解决方案可能是使用OrderedDict或使用 dict 与维护排序的列表相结合。

sort(score.keys())
sort(sports)

Try this and print both of them试试这个并打印它们

If your list has the same values as the key of the dictionary, why would you want to sort the list?如果您的列表与字典的键具有相同的值,为什么要对列表进行排序? Just take the keys of the dictionary, similar to what Renaud suggests:只需获取字典的键,类似于 Renaud 的建议:

sports = list(score)

If you are using a Python version that does not yet guarantee an order of dictionary entries, then of course the whole point is moot.如果您使用的 Python 版本还不能保证字典条目的顺序,那么整个问题当然是没有意义的。

If you want some behavior for cases where the list of sports and the keys of scores are not the same (set-wise), then you should define that behavior.如果您希望在运动列表和分数键不相同(按集合方式)的情况下采取某种行为,那么您应该定义该行为。

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

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