1

im newbie in Python and i got task to sort dates in dictionary by year, month, day.

I found one nice method from W3Schools but i dont know how to work one thing. Below is code

def myFunc(e):
  return e['year']

cars = [
  {'car': 'Ford', 'year': 2005},
  {'car': 'Mitsubishi', 'year': 2000},
  {'car': 'BMW', 'year': 2019},
  {'car': 'VW', 'year': 2011}
]

cars.sort(key=myFunc)

print(cars)

Its working good to sort for example cars by year, also to dates by year, month, day but i have question. How this method is working and why there is 'e' which i didnt use in cars.sort(key=myFunc)? Why this 'key=myFunc' myFunc is without argument? Can i write it without this function? My main language is Java so its abstract for me and maybe someone can explain this.

def myFunc(e):
  return e['year']

I have read doc about sort but still i dont understand this function.

1
  • 1
    From the docs: key specifies a function of one argument that is used to extract a comparison key from each list element The sort algorithm will call the function for each element in the list, passing that element as an argument. The function should return the value to use in the sort. Commented Mar 3, 2021 at 22:16

1 Answer 1

2

In python you can pass functions as arguments. sort can take a function as its sorting key. I suggest looking up tutorials on python syntax, functions, python dict, and sorting lists.

To answer your question briefly, cars is a list that has multiple dictionary elements. cars.sort() needs to know how to sort these elements (there is no clear way to sort something abstract like that).

That's where key=myFunc comes in handy. cars.sort() will give myFunc an element, then myFunc receives that element as whatever parameter you have in its header. Here, you have e as the dictionary element since def myFunc(e) is your header. The function returns the year of the dictionary element by getting e['year']. This year is returned to the cars.sort() which now knows that it must sort the dictionary elements by this year value that was returned.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.