[英]Sort list using dictionary key values
Lets say i have a list to sort of 可以说我有一个清单
list_values = ['key3', 'key0', 'key1', 'key4', 'key2']
And a order dict of 和命令的命令
ordered_dict = OrderedDict([('key4', 0), ('key1', 1), ('key2', 2), ('key0', 3), ('key3', 4)])
How can i sort the list_values
using the ordered_dict
key accordingly? 如何使用ordered_dict
键对list_values
进行排序?
ie:- sorted_list = ['key4', 'key1', 'key2', 'key0', 'key3']
即: sorted_list = ['key4', 'key1', 'key2', 'key0', 'key3']
EDIT: Since almost all of the answers solves the problem, what is the most suitable and perfect pythonic way of doing this? 编辑:由于几乎所有的答案都可以解决问题,什么是最合适,最完美的pythonic方法?
Call list.sort
, passing a custom key
: 调用list.sort
,传递一个自定义key
:
list_values.sort(key=ordered_dict.get)
list_values
# ['key4', 'key1', 'key2', 'key0', 'key3']
Alternatively, the non-in-place version is done using, 另外,非就地版本也可以使用
sorted(list_values, key=ordered_dict.get)
# ['key4', 'key1', 'key2', 'key0', 'key3']
If we assume that list is subset of dict: 如果我们假设列表是dict的子集:
list_values = ['key3', 'key1']
ordered_dict = OrderedDict([('key4', 0), ('key1', 1), ('key2', 2), ('key0', 3), ('key3', 4)])
output = [v for v in ordered_dict if v in list_values]
print(output)
→ →
['key1', 'key3']
Example 2: 范例2:
list_values = ['key3', 'key0', 'key1', 'key4', 'key2']
ordered_dict = OrderedDict([('key4', 0), ('key1', 1), ('key2', 2), ('key0', 3), ('key3', 4)])
output = [v for v in ordered_dict if v in list_values]
print(output)
→ →
['key4', 'key1', 'key2', 'key0', 'key3']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.