Home > OS >  check if a list of dict is in ascending value and return the incorrect dict
check if a list of dict is in ascending value and return the incorrect dict

Time:10-15

Dict below is just for example purpose:

a = [{'name':'sally','age':'31'},{'name':'greg','age':'30'},{'name':'josh','age':'32'},{'name':'bobby','age':'33',]

The order of the dict need to follow the age. So i need to check if the dict is in order or not and print their 'name' if the age not in order.

What i did so far was sorted out the list of dict according to their age (ascending)

sorted_age = sorted(a, key=lambda d: d['age'])

and compare both dict to see if they are equal or not.

 if a == sorted_age:
            continue
        else:
            print(False)

I need to print 'sally' and 'greg' as their age are not in order. and i dont know how to print their name

CodePudding user response:

You can use zip:

[(a, b) for a, b in zip(data, data[1:]) if a['age'] > b['age']]

[({'name': 'sally', 'age': '31'}, {'name': 'greg', 'age': '30'})]

CodePudding user response:

Just iterate through the dicts:

for da, ds in zip(a, sorted_age):
    if da != ds:
        print(da['name'])
print('are not in order')
  • Related