1

I have a list of dictionary named code[] which has values

[{'sectionnumber': '1010.1.9.1', ...},
{'sectionnumber': '1010.1.9.2', ...}
{'sectionnumber': '1010.1.9', ...},
{'sectionnumber': '1010.1.9.10', ...}]

and I want to sort them by sectionnumber. I tried using :

codelist = sorted(codelist, key=lambda codelist:codelist["sectionnumber"])

but it returns

[{'sectionnumber': '1010.1.9', ...},
{'sectionnumber': '1010.1.9.1', ...}
{'sectionnumber': '1010.1.9.10', ...},
{'sectionnumber': '1010.1.9.2', ...}]

when it supposed to be

[{'sectionnumber': '1010.1.9', ...},
{'sectionnumber': '1010.1.9.1', ...}
{'sectionnumber': '1010.1.9.2', ...},
{'sectionnumber': '1010.1.9.10', ...}]
Eric Lin
  • 39
  • 6
  • Hello, regarding `sorted(codelist, key=lambda codelist:codelist["sectionnumber"])`: this line is technically correct, but I strongly encourage you **not** to name every variable with the same name. Here the list of pairs is named `codelist` and the pairs are named `codelist` too. I suggest using different names for different things. For instance `codelist = sorted(codelist, key=lambda x: x["sectionnumber"])` – Stef Dec 29 '22 at 15:57

0 Answers0