如何通过 2 个键对字典列表进行排序,其中一个键基于任意列表
我正在使用Python。 如何首先按“日”然后按“工作”对下面的词典列表进行排序。
“工作”的排序需要基于priority_list(不是按字母顺序):
priority_list= ['c','a','b']
my_list_of_dicts = [
{'day':5,'job':'c','irrelevant_key':'more stuff'},
{'day':1,'job':'a','irrelevant_key':'stuff'},
{'day':5,'job':'b','irrelevant_key':'more stuff'},
{'day':1,'job':'b','irrelevant_key':'other stuff'}
]
排序结果应该是:
[{'day':1,'job':'a','irrelevant_key':'stuff'},
{'day':1,'job':'b','irrelevant_key':'other stuff'},
{'day':5,'job':'c','irrelevant_key':'more stuff'},
{'day':5,'job':'b','irrelevant_key':'more stuff'}]
非常感谢,
I'm using python.
How do I sort the list of dictionaries below first by 'day' then by 'job'.
The sort on 'job' needs to be based on priority_list (not alphabetically):
priority_list= ['c','a','b']
my_list_of_dicts = [
{'day':5,'job':'c','irrelevant_key':'more stuff'},
{'day':1,'job':'a','irrelevant_key':'stuff'},
{'day':5,'job':'b','irrelevant_key':'more stuff'},
{'day':1,'job':'b','irrelevant_key':'other stuff'}
]
result of sorting should be:
[{'day':1,'job':'a','irrelevant_key':'stuff'},
{'day':1,'job':'b','irrelevant_key':'other stuff'},
{'day':5,'job':'c','irrelevant_key':'more stuff'},
{'day':5,'job':'b','irrelevant_key':'more stuff'}]
Thanks very much,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于非常小的列表(例如您的示例),使用
list.index()
的答案将可以正常工作。但是,如果列表很大,则值得花时间从
priority_list
构建一个dict
。dict
查找的时间复杂度为 O(1),而list
查找的时间复杂度为 O(N)。For a very small list, such as your example, the answers using
list.index()
will work fine.However, if the list is large, it would be worth the time to build a
dict
out of thepriority_list
.dict
lookups are O(1), whilelist
lookups are O(N).