|
| 1 | +from operator import itemgetter |
| 2 | + |
| 3 | +users = [ |
| 4 | + {'fname': 'Bucky', 'lname': 'Roberts'}, |
| 5 | + {'fname': 'Tom', 'lname': 'Roberts'}, |
| 6 | + {'fname': 'Bernie', 'lname': 'Zunks'}, |
| 7 | + {'fname': 'Jenna', 'lname': 'Hayes'}, |
| 8 | + {'fname': 'sally', 'lname': 'Jones'}, |
| 9 | + {'fname': 'Amanda', 'lname': 'Roberts'}, |
| 10 | + {'fname': 'Tom', 'lname': 'Williams'}, |
| 11 | + {'fname': 'Dean', 'lname': 'Hayes'}, |
| 12 | + {'fname': 'Bernie', 'lname': 'Barbie'}, |
| 13 | + {'fname': 'Tom', 'lname': 'Jones'} |
| 14 | +] |
| 15 | + |
| 16 | +# How to sort when there are more than 1 keys |
| 17 | + |
| 18 | +for x in sorted(users, key = itemgetter('fname')): # keyword 'sorted' takes in 3 values: 1. the dictionary 2. the key 3. reverse = True/False |
| 19 | + # 'itemgetter' allows us to fetch the keyword with which we want to sort the items in the given dictionary |
| 20 | + |
| 21 | + print(x) # But the problem here is it sorts the 1st name accordingly bt the last names aren't sorted |
| 22 | + |
| 23 | +print('______________________________________\n') |
| 24 | + |
| 25 | +# How to fix this problem |
| 26 | + |
| 27 | +for x in sorted(users, key = itemgetter('fname', 'lname')): # Here we can even use 2 keys, but the 1st one will be given preference |
| 28 | + print(x) |
0 commit comments