Home > Dive Into Python > Getting To Know Python > Mapping lists | << >> |
diveintopython.org | |
Python for experienced programmers | |
List mapping is a powerful way to transform data by applying a function to every element in a list.
Example 1.28. List mapping in buildConnectionString
["%s=%s" % (k, params[k]) for k in params.keys()]
First, notice that you're calling the keys function of the params dictionary. This function simply returns a list of all the keys in the dictionary.
Example 1.29. The keys function
>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"} >>> params.keys() ['server', 'uid', 'database', 'pwd']
The list is in no particular order (remember, elements in a dictionary are unordered), but it is a list, and that means you can map it. Mapping works by looping through a list and applying a function to each element, then returning a new list with those calculated values.
Example 1.30. Introducing list mapping
>>> li = [1, 9, 8, 4] >>> [elem*2 for elem in li][2, 18, 16, 8] >>> li
[1, 9, 8, 4]
Now you should understand what the code in buildConnectionString does. It takes a list, params.keys(), and maps it to a new list by applying the string formatting to each element. The new list will have the same number of elements as params.keys(), but each element in the new list will contain both a key and its associated value from the params dictionary.
Example 1.31. List mapping in buildConnectionString, step by step
>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"} >>> params.keys() ['server', 'uid', 'database', 'pwd'] >>> [k for k in params.keys()]['server', 'uid', 'database', 'pwd'] >>> [params[k] for k in params.keys()]
['mpilgrim', 'sa', 'master', 'secret'] >>> ["%s=%s" % (k, params[k]) for k in params.keys()]
['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
![]() | The trivial case of list mapping. The mapping expression is just the element itself, so this list mapping returns a verbatim copy of the list. This is equivalent to params.keys(). |
![]() | A less trivial mapping. Iterating through params.keys(), the variable k is assigned each element in turn, and the mapping expression takes that element and looks up the corresponding value in the params dictionary. This is equivalent to params.values(). |
![]() | Combining the previous two examples with some simple string formatting, we get a list of key-value pairs. This looks suspiciously like the output of the program; all that remains is to join the elements in this list into a single string. |
« Formatting strings | Joining lists and splitting strings » |