I want to compare two lists and verify if they are the same. Though the lists might have items in a different order so just comparing list1 == list2
would not work.
Those lists can be nested into multi-level with dicts, strings, integers, and lists, so just using sorted(list1) == sorted(list2)
would not work either.
I'm trying to create a function that iterates through a multi-level list and sort each list inside of it in ascending order.
The results I'm having so far only sorts the first level main
list. All the other "sub lists" get sorted inside the function but when I print the final result they are unsorted the same way before using the function.
Function created so far:
def sort_multilevel_obj(items):
if isinstance(items, dict):
for v in items.values():
if isinstance(v, list):
v = sorted(v)
v = sort_multilevel_obj(v)
if isinstance(items, list):
items = sorted(items)
for i in items:
i = sort_multilevel_obj(i)
return items
Example of multi-level list:
mylist = [
'string1',
[
{
1:'one',
2:'two',
3:[4,2,'ddd'],
4:{'x':'xx'}
},
'substring'
],
{
'somekey':7,
'anotherkey':[
'ccccccc',
100,
4,
'blabla'
]
}
]
When I pass the list into the function the result I got is:
[{'z': ['ccccccc', 100, 4, 'afsafas'], 'f': 7}, [{1: 'one', 2: 'two', 3: [4, 2, 'ddd'], 4: {'x': 'xx'}}, 'substring'], 'string1']
The fist list (string, list, dict) is sorted properly (to dict, list, string) but the list inside the dict (['ccccccc', 100, 4, 'afsafas']
) should be returned as [4, 100, 'afsafas', 'ccccccc']
but this just doesn't work.
What am I doing wrong?