Issues Sorting a list, list out of order

Rich

enter image description here

Hi, I'm trying to write a basic GUI using python and pytq5 which displays information received from an API call, when the information is returned from the API it seems to be out of order and i cant figure out how to sort the data before i send it to the GUI, the list is a list of dictionaries,

interfaces = [
        {'name': 'GigabitEthernet 0/0'},
        {'name': 'GigabitEthernet 1/0/1'},
        {'name': 'GigabitEthernet 1/0/10'},
        {'name': 'GigabitEthernet 1/0/11'},
        ...        
        ]

Any advice would be appreciated, from the image i would be expecting to sort the data so that 1/0/1 - 1/0/9 are all before 1/0/10

Thanks

Yılmaz Alpaslan

Try this:

# Your list of dicts
interfaces = [
    {'name': 'GigabitEthernet 0/0'},
    {'name': 'GigabitEthernet 1/0/11'},
    {'name': 'GigabitEthernet 1/0/10'},
    {'name': 'GigabitEthernet 1/0/1'},
    {'name': 'GigabitEthernet 1/0/2'}
]

new_interfaces = []
# Create a list of dicts whose value corresponding to the 'name' key would be a list
# containing the ethernet type (in this case, 'GigabitEthernet') and a list of 3
# elements representing the date (like '[1, 0, 11]')
for entry in [i["name"] for i in interfaces]:
    new_interfaces.append({'name': [entry.split()[0], entry.split()[1].split("/")]})

# If one of those lists representing the date contains 2 elements, add a third
# element with a value of '0'
for entry in new_interfaces:
    if len(entry['name'][1]) == 2:
        entry['name'][1].append('0')

# Sort the list according to the date
new_interfaces = sorted(new_interfaces, key=lambda d: int(''.join(d['name'][1])))

# Re-create the original list with sorted values and original structure
interfaces = []
for entry in new_interfaces:
    interfaces.append({'name': f"{entry['name'][0]} {'/'.join(entry['name'][1])}"})
print(interfaces)

Output:

[{'name': 'GigabitEthernet 0/0/0'}, {'name': 'GigabitEthernet 1/0/1'}, {'name': 'GigabitEthernet 1/0/2'}, {'name': 'GigabitEthernet 1/0/10'}, {'name': 'GigabitEthernet 1/0/11'}]

This algorithm converts the date (or whatever it is lol) to a string without '/'s so that it can be converted to an integer to be able to be compared with each other properly.

Example:

1/0/10 would be 1010

1/0/1 would be 101

And as 101 is lower than 1010 as a number, sorted() method puts it to front.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related