Reputation: 35
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.
Upvotes: 1
Views: 94
Reputation: 450
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.
Upvotes: 2