Python Forum
get method within max function for a dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
get method within max function for a dictionary
#4
What you've learnt here is that functions can be treated as values in Python and so can be passed around to other functions. This is quite a useful, powerful idea, because it means you can build quite generic functions that can be reused in different ways, by passing in different functions. That seems a bit abstract, so let's look at some examples:

Let's say I have a list of numbers and I want to double each of them, or I have a list of strings and want to turn them into uppercase. The thing in common here is wanting to do something to each item in the list; it's just that the "something" varies. The map function is the kind of generic function I'm talking about. It takes a list (or other iterable) and a function to call on each item:

>>> values = [1, 2, 3, 4]
>>> def double(x):
...     return 2 * x
... 
>>> list(map(double, values))
[2, 4, 6, 8]
>>> words = ["hello", "goodbye", "dog", "cat"]
>>> def uppercase(word):
...     return word.upper()
... 
>>> list(map(uppercase, words))
['HELLO', 'GOODBYE', 'DOG', 'CAT']
>>> 
A couple things to note here:

1. Using map might not be considered the most idiomatic Python - normally I'd use a list comprehension for these but I'm specifically using map to illustrate the point.

2. I have to call list on the return value of map because it doesn't return a list, but rather a kind of lazy sequence. Essentially that means that each of the items in that sequence is computed on demand when it's accessed, so printing the object you get back wouldn't be much use.

This idea of higher order functions (those that either take functions as arguments, or return them) is quite commonplace in many programming languages today.
Reply


Messages In This Thread
RE: get method within max function for a dictionary - by ndc85430 - Jul-03-2020, 05:55 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to use value in dictionary as arguments in function gabejohnsonny21 6 3,830 Apr-22-2020, 04:53 PM
Last Post: deanhystad
  Why is this function printing the number of keys in a dictionary? mafr97 5 3,100 Sep-17-2019, 06:19 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020