diveintopython.org
Python for experienced programmers

 

1.12. Mapping lists

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] 1
[2, 18, 16, 8]
>>> li                      2
[1, 9, 8, 4]
1 To make sense of this, look at it from right to left. li is the list you're mapping. Python loops through li one element at a time, temporarily assigning the value of each element to the variable elem. Python then applies the function elem*2 and appends that result to the returned list.
2 Note that list mapping does not change the mapped list.

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()]                        1
['server', 'uid', 'database', 'pwd']
>>> [params[k] for k in params.keys()]                2
['mpilgrim', 'sa', 'master', 'secret']
>>> ["%s=%s" % (k, params[k]) for k in params.keys()] 3
['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
1 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().
2 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().
3 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.