1

So I have a Person class derived from dict that contains details like first name, last name, and id.

I have the data loaded from a json file into object and instantiated person class per person in the json (about 30 people) and put them in a peopleList list in the following code:

import json

class Person(dict):
    def __init__(self, firstname, lastname, personID):
        super().__init__()
        self.firstname = firstname
        self.lastname = lastname
        self.personID = personID

peopleList = []

with open('data.json', 'r') as peopleData:
    dataObject = json.load(peopleData)

    for registrant in dataObject['registrants']:
        newperson = Person(registrant["firstname"], registrant["lastname"], registrant["personID"])

        peopleList.append(newperson)

Now I'm trying write a function that takes the peopleList and criteria parameter. This function will sort the list based in alphabetical order based on criteria (firstname, or lastname, or even ID)

Trying to use the peopleList.sort() menthod and failing hard with this. Any input from you guys would be greatly appreciated here. :)

RDudek
  • 23
  • 3
  • From the suggested duplicate - `peopleList = sorted(peopleList, key=lambda x: x.firstname)` for example. – roganjosh Dec 05 '17 at 19:27
  • @roganjosh That worked! Thanks! – RDudek Dec 05 '17 at 19:39
  • @Maurice Meyer, I followed that link and for some reason could not get it to work with my setup. I think I mistyped something there. – RDudek Dec 05 '17 at 19:40
  • There is a difference between `sort` and `sorted`. The comment I posted, which uses `sorted` does _not_ work in-place, which is why I assigned the result back to `peopleList` (but I could have called the result anything I wanted). `sort` _does_ work in place, so don't assign the result back to anything, you'll get `None`. `peopleList.sort(key = lambda x: x.firstname)` would be the way in that case. Maybe that was the issue? – roganjosh Dec 05 '17 at 19:43

0 Answers0