1

I have the following dictionary:

employees = [

    {'Name': 'Alan Turing', 'age': 25, 'salary': 10000},

    {'Name': 'Sharon Lin', 'age': 30, 'salary': 8000},

    {'Name': 'John Hopkins', 'age': 18, 'salary': 1000},

    {'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000},

]

I now want to sort this dictionary with the key 'age' using Lambda. You can find below how I tried to figure this out:

print(list(map(employees.sort(key = lambda x: x.get('age')), employees)))

I get the following error:

Traceback (most recent call last):

  File "<string>", line 10, in <module>

TypeError: 'NoneType' object is not callable

How should I configure the lambda to get the correct output?

Thank you!

Gabio
  • 9,126
  • 3
  • 12
  • 32
rodny9
  • 53
  • 1
  • 4
  • [`list.sort`](https://docs.python.org/3/library/stdtypes.html#list.sort) returns `None` to "remind users it operates by side effect". Just use `employees.sort(key = lambda x: x.get('age')) print(employees)` – Nick Jun 30 '20 at 11:48

1 Answers1

1

You want to use sorted instead of sort. The former returns a new array while the latter does the sorting in place.

print(list(sorted(employees, key = lambda x: x.get('age'))))

If you do want to sort in place, your version of employees.sort(key=lambda x: x.get('age')) works correctly. The call to sort doesn't return anything though, so if you want to verify the result, add another call to print

employees.sort(key=lambda x: x.get('age'))
print(employees)
Milan Cermak
  • 7,476
  • 3
  • 44
  • 59
  • Thank you, but what is wrong with using map and sort() instead of sorted, more or less both look very similar? – rodny9 Jun 30 '20 at 11:50
  • There's nothing wrong with using sort. You cannot use map() and sort() together like this though. The call to sort() returns `None` which would be the input to map, that does not work. – Milan Cermak Jun 30 '20 at 13:23