0

I am trying to sort a list which has 3 dictionaries.

l = [
    {'Index': 3},
    {'Index': 1},
    {'Index': 2}
]

sorted(l, key=lambda l:l['Index'])

print(l)

what I expected for answer is

[{'Index': 1}, {'Index': 2}, {'Index': 3}]

but the actual answer is

[{'Index': 3}, {'Index': 1}, {'Index': 2}]

where should I fix the code for the answer?

bharatk
  • 4,202
  • 5
  • 16
  • 30
MinJae
  • 18
  • 1

1 Answers1

1
from operator import itemgetter

l = [
    {'Index': 3},
    {'Index': 1},
    {'Index': 2}
]

newlist = sorted(l, key=itemgetter('Index'))
print(newlist)

or just reassign it to itself like you did it.

l = sorted(l, key=lambda l:l['Index'])
Kostas Charitidis
  • 2,991
  • 1
  • 12
  • 23