1

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?

Masoud Rahimi
  • 5,785
  • 15
  • 39
  • 67
tbuissa
  • 21
  • 2
  • You're creating `i` & `v` but not using them anywhere. – rdas May 09 '19 at 19:02
  • Which exactly python version are you using? I tried run the code and caught this exception: `TypeError: '<' not supported between instances of 'list' and 'str'` – Kafels May 09 '19 at 19:39

1 Answers1

0

Try using v.sort() instead of v = sorted(v). v.sort() mutates the original list while sorted(v) returns a new object. See this answer for another explanation about the difference between v.sort() and sorted(v).

The reason why v = sorted(v) doesn't change the value in the list/dict itself is because the variable v is basically only a reference to the original value in the dict/list. When you use v = <something> you're pointing that variable to another object and thus not changing the original value.

D Malan
  • 10,272
  • 3
  • 25
  • 50