1

I have noticed that in some cases "what you want to do" to an object is written before the object while other times the object is written first.

here is an example

dictionary = {}

dictionary["ole"] = 28
dictionary["maria"] = 26
dictionary["kim"] = 6
dictionary["lucy"] = 1

print(dictionary.keys()) # object first (dictionary)

print(sorted(dictionary)) # object after (sorted()) is first

How do I know when the object should be before "what I want to do with it" or after?

  • 1
    Technically, `.keys()` is a method of a `dict`, but `sorted()` is a function which takes a container as a parameter. But, yes, confusing until you 'know'. – quamrana Apr 22 '19 at 11:20
  • *How do I know when the object should be before "what I want to do with it" or after?* - By reading the documentation and learning. – mkrieger1 Apr 22 '19 at 11:28

1 Answers1

1

Sorted is a function that operates on an object, but exists outside of the objects class (a decision that python community made), while .keys is a method of a dictionary. I.e it exists inside the dict class. Moreover, sorted() builtin function can sort also lists and other iterables, and if it was a method internal to dict, then every other iterable type would need its own such method with basically the same code inside. To me that would violate KISS and DRY principles.

There was a proposition to add such a method to dict class, but was turned down by BDFL (read: Benevolent Dictator For Life, Guido van Rossum, the creator of python), on the grounds that this functionalready does the same thing.

You can overload the dict class and add your own sorting method in your projects, if you please.

As for knowing when to use a builtin function, there are only a handful of those (https://docs.python.org/3/library/functions.html) so other than one of those, you would look for a method specific to the class you currently deal with

Ilia Gilmijarow
  • 1,000
  • 9
  • 11