I have 2 quite nested Python dictionaries and I would like to compare them (My real Json files contains hundred thousands lines). These dictionaries contain lists and these lists contain dictionaries. The order of elements are not fixed and it is not problem in case of dictionary but it is in case of a list. So I have to sort the elements in my structure.
I have written an sorting algorithm which sorts the items recursively in my data structure.
My code works as expected with Python2.7 executable but it doesn't work with Python3.6.6 executable.
I have already read the official Python documentation and I know that the list.sort() has been changed between Python2 and Python3, but I feel it is a quite big limitation in Python3.
I am familiar with the key parameter but it doesn't solve my problem. Furthermore, the keys are not the same in the dicts.
So, my question: Is it possible to sort a list which contains more type elements like in my case?
Code:
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))
Output with 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
Output with 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'