-1

I was able to sort a list of objects by a string attribute using this excellent post:

How to sort a list of objects based on an attribute of the objects?

However, I also need the sort to ignore case when alphabetizing. Suppose I had a list of objects that each had an attribute "Name":

class MyObject (object):
   def __init__(self):
      MyObject.Name = None

itemsList = []

object1 = MyObject()
object1.Name = "Orange"
itemsList.append(object1)

object2 = MyObject()
object2.Name = "apple"
itemsList.append(object2)

object3 = MyObject()
object3.Name = "Banana"
itemsList.append(object3)

I can sort them like this:

itemsList.sort(key=lambda item : item.Name)

But how do I also ignore case? I tried throwing lower onto Name at that last line but it didn't work for me.

secretagentmango
  • 393
  • 1
  • 6
  • 15
  • 3
    Did you throw `lower` onto `Name`, or `lower()`? The latter should work. – tobias_k Aug 07 '18 at 14:01
  • @tobias_k Ah, you are correct. Thank you! – secretagentmango Aug 07 '18 at 14:03
  • If the answer is that trivial, feel free to delete. – Mad Physicist Aug 07 '18 at 14:06
  • Be careful. In your `__init__` method you're actually defining a class-level attribute instead of an instance attribute. You just happen to assign to an instance attribute when you do `instance.Name = ...`. If you try to do this with mutable objects, your code will display some very add behaviour. You should assign instance attributes in `__init__` using `self`: `self.name = None` – Patrick Haugh Aug 07 '18 at 14:06
  • Also, it's `self.Name = None`, not `MyObject.Name = None`, and it's conventional to use lowercase-with-underscore attribute names in Python. – Mad Physicist Aug 07 '18 at 14:07

1 Answers1

2

As suggested, compare the strings after mapping them to lower case letters:

itemsList.sort(key=lambda item : item.Name.lower())
Learning is a mess
  • 3,886
  • 3
  • 24
  • 56