python - 在 Python3 中对包含字典的列表进行排序

标签 python python-3.x list sorting dictionary

我有 2 个相当嵌套的 Python 字典,我想比较它们(我的真实 Json 文件包含数十万行)。这些字典包含列表,这些列表包含字典。元素的顺序不固定,这在字典的情况下不是问题,但在列表的情况下。所以我必须对结构中的元素进行排序。

我编写了一个排序算法,可以对我的数据结构中的项目进行递归排序。

我的代码在 Python2.7 可执行文件中按预期工作,但在 Python3.6.6 可执行文件中不起作用。

我已经阅读了 Python 官方文档,我知道 list.sort() 在 Python2 和 Python3 之间发生了变化,但我觉得这在 Python3 中是一个很大的限制。

我熟悉 key 参数,但它不能解决我的问题。此外,字典中的键也不相同。

那么,我的问题是:是否可以对包含更多类型元素的列表进行排序,就像我的情况一样?

代码:

test_1 = {"aaa": 111, "bbb": 222, "ccc": [{"o": [1, "t"]}, "a", "b", 1, [1, 2, [4, 3, [6, 5]]]]}
test_2 = {"bbb": 222, "aaa": 111, "ccc": [[2, 1, [3, 4, [5, 6]]], 1, "a", "b", {"o": ["t", 1]}]}


def list_sort(l):
    if isinstance(l, list):
        l.sort()
        for x in l:
            list_sort(x)


def dict_sorter(d):
    for k, v in d.items():
        if isinstance(v, dict):
            dict_sorter(v)
        elif isinstance(v, list):
            v.sort()
            for x in v:
                if isinstance(x, dict):
                    dict_sorter(x)
                elif isinstance(x, list):
                    list_sort(x)


print("\n\nBEFORE:")
print(test_1)
print(test_2)
print("EQ: {}".format(test_1 == test_2))

dict_sorter(test_1)
dict_sorter(test_2)

print("\n\nAFTER:")
print(test_1)
print(test_2)
print("EQ: {}".format(test_1 == test_2))

用 Python2 输出:

>>> python2 test.py

BEFORE:
{'aaa': 111, 'bbb': 222, 'ccc': [{'o': [1, 't']}, 'a', 'b', 1, [1, 2, [4, 3, [6, 5]]]]}
{'aaa': 111, 'bbb': 222, 'ccc': [[2, 1, [3, 4, [5, 6]]], 1, 'a', 'b', {'o': ['t', 1]}]}
EQ: False

AFTER:
{'aaa': 111, 'bbb': 222, 'ccc': [1, {'o': [1, 't']}, [1, 2, [3, 4, [5, 6]]], 'a', 'b']}
{'aaa': 111, 'bbb': 222, 'ccc': [1, {'o': [1, 't']}, [1, 2, [3, 4, [5, 6]]], 'a', 'b']}
EQ: True

用 Python3 输出:

>>> python3 test.py

BEFORE:
{'aaa': 111, 'bbb': 222, 'ccc': [{'o': [1, 't']}, 'a', 'b', 1, [1, 2, [4, 3, [6, 5]]]]}
{'bbb': 222, 'aaa': 111, 'ccc': [[2, 1, [3, 4, [5, 6]]], 1, 'a', 'b', {'o': ['t', 1]}]}
EQ: False
Traceback (most recent call last):
  File "test.py", line 30, in <module>
    dict_sorter(test_1)
  File "test.py", line 17, in dict_sorter
    v.sort()
TypeError: '<' not supported between instances of 'str' and 'dict'

最佳答案

在 python2 中,任何数据与任何其他数据之间的比较都是可能的。但是,在 python3 中这是不可能的。

[引用]

https://portingguide.readthedocs.io/en/latest/comparisons.html

关于python - 在 Python3 中对包含字典的列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62831955/

相关文章:

python - “elif”在 'while' 循环内不起作用

python - 在 Python 中检测 OHLC 数据中的模式

python - 迭代 2 个字典并比较值,然后附加内部列表

python - 通过字典访问函数

python - PyPlot 不绘制图像

python - Reportlab PDF版本生成问题

python - 获取计算机硬件信息

python - 如何更改 matplotlib - spyder 中的默认绘图颜色?

python-3.x - Python Selenium 从某些类中获取值

c# - 使用 LINQ 将 List<int> 转换为 Dictionary<int,int>