如何使用排序的键列表对OrderedDict进行排序? [英] How to sort OrderedDict using a sorted list of keys?

查看:238
本文介绍了如何使用排序的键列表对OrderedDict进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个collections.OrderedDict对象和它的键的重新排列列表:

Suppose I have a collections.OrderedDict object and a re-arranged list of its keys:

ordereddict = collections.OrderedDict((
    ('key_78', 'value'),
    ('key_40', 'value'),
    ('key_96', 'value'),
    ('key_53', 'value'),
    ('key_04', 'value'),
    ('key_89', 'value'),
    ('key_52', 'value'),
    ('key_86', 'value'),
    ('key_16', 'value'),
    ('key_63', 'value'),
))

# Example only; actual list will **not** == sorted(ordereddict)
key_list = ['key_04', 'key_16', 'key_40', 'key_52', 'key_53', 'key_63', 'key_78', 'key_86', 'key_89', 'key_96']

如何对OrderedDict进行排序,以便以与key_list相同的方式进行排序?

How can I sort the OrderedDict so that it is ordered in the same way as the key_list?

推荐答案

使用以下内容:

def sort_by_list(dict_, list_):
    for key in list_:
        dict_.move_to_end(key)

sort_by_list(ordereddict, key_list)

仅当list_包含字典中的所有键以及在Python 3.2或更高版本上时,此方法才有效.

This only works if the list_ contains all the keys in the dict, and on Python 3.2 or later.

这篇关于如何使用排序的键列表对OrderedDict进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆