You are here: Home > Dive Into Python > Getting To Know Python > Mapping lists | << >> | ||||
Dive Into PythonPython for experienced programmers |
One of the most powerful features of Python is the list comprehension, which provides a compact way of mapping a list into another list by applying a function to each of the elements of the list.
>>> li = [1, 9, 8, 4] >>> [elem*2 for elem in li] [2, 18, 16, 8] >>> li [1, 9, 8, 4] >>> li = [elem*2 for elem in li] >>> li [2, 18, 16, 8]
["%s=%s" % (k, v) for k, v in params.items()]
First, notice that you’re calling the items function of the params dictionary. This function returns a list of tuples of all the data in the dictionary.
>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"} >>> params.keys() ['server', 'uid', 'database', 'pwd'] >>> params.values() ['mpilgrim', 'sa', 'master', 'secret'] >>> params.items() [('server', 'mpilgrim'), ('uid', 'sa'), ('database', 'master'), ('pwd', 'secret')]
Now let’s see what buildConnectionString does. It takes a list, params.items(), and maps it to a new list by applying string formatting to each element. The new list will have the same number of elements as params.items(), but each element in the new list will be a string that contains both a key and its associated value from the params dictionary.
>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"} >>> params.items() [('server', 'mpilgrim'), ('uid', 'sa'), ('database', 'master'), ('pwd', 'secret')] >>> [k for k, v in params.items()] ['server', 'uid', 'database', 'pwd'] >>> [v for k, v in params.items()] ['mpilgrim', 'sa', 'master', 'secret'] >>> ["%s=%s" % (k, v) for k, v in params.items()] ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
Note that we’re using two variables to iterate through the params.items() list. This is another use of multi-variable assignment. The first element of params.items() is ('server', 'mpilgrim'), so in the first iteration of the list comprehension, k will get 'server' and v will get 'mpilgrim'. In this case we’re ignoring the value of v and only including the value of k in the returned list, so this list comprehension ends up being equivalent to params.keys(). (You wouldn’t really use a list comprehension like this in real code; this is an overly simplistic example so you can get your head around what’s going on here.) | |
Here we’re doing the same thing, but ignoring the value of k, so this list comprehension ends up being equivalent to params.values(). | |
Combining the previous two examples with some simple string formatting, we get a list of strings that include both the key and value of each element of the dictionary. 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 |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | |
Joining lists and splitting strings >> |