Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python3.x中,有没有更好的方法对复杂字典进行排序?_Python_Sorting_Python 3.x_Dictionary - Fatal编程技术网

在Python3.x中,有没有更好的方法对复杂字典进行排序?

在Python3.x中,有没有更好的方法对复杂字典进行排序?,python,sorting,python-3.x,dictionary,Python,Sorting,Python 3.x,Dictionary,我需要比较JSON对象,它有时可以大到400KB。我选择使用Python3.5来实现这一点 rapidjson和ultrajson都将很快将这些对象解码到Python字典和列表中 我的问题是,这些字典和字典列表需要排序,因为JSON对象是无序的 我提出了这段代码,它以元组列表的形式进行排序,然后转换为OrderedDict: from collections import OrderedDict def sort_me(unsorted): if isinstance(unsorte

我需要比较JSON对象,它有时可以大到400KB。我选择使用Python3.5来实现这一点

rapidjson和ultrajson都将很快将这些对象解码到Python字典和列表中

我的问题是,这些字典和字典列表需要排序,因为JSON对象是无序的

我提出了这段代码,它以元组列表的形式进行排序,然后转换为OrderedDict:

from collections import OrderedDict


def sort_me(unsorted):
    if isinstance(unsorted, dict):
        return sorted((k, sort_me(v)) for k, v in unsorted.items())
    if isinstance(unsorted, list):
        return sorted(sort_me(x) for x in unsorted)
    else:
        return unsorted


def to_ordered_dict(sort_of):
    if isinstance(sort_of, list):
        ordered = OrderedDict()
        if sort_of and isinstance(sort_of[0], list):
            ordered = []
            for i in sort_of:
                ordered.append(to_ordered_dict(i))
            return ordered
        else:
            for i in sort_of:
                if isinstance(i, list):
                    ordered.update(to_ordered_dict(i))
                elif isinstance(i, tuple):
                    ordered[i[0]] = to_ordered_dict(i[1])
            return ordered
    else:
        return sort_of

done = to_ordered_dict(sort_me(large_dict))
这似乎不是最好的方法,因为我至少要浏览对象两次。有没有更好的方法来做到这一点,这样我就不会在字典里翻两遍了?

我想这正是你想要的,尽管它不是一个官方图书馆。基本上,它会对添加的项目进行排序。我想这就是你想要的,虽然它不是一个官方图书馆。基本上,它会对添加的项目进行排序。