{article Dive into Python}{title} {text}{/article}

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.


Introducing List Comprehensions

  1. li = [1, 9, 8, 4]
  2. [elem*2 for elem in li]
  3. li = [elem*2 for elem in li]

  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 comprehensions do not change the original list.
  3. It is safe to assign the result of a list comprehension to the variable that you're mapping. Python constructs the new list in memory, and when the list comprehension is complete, it assigns the result to the variable


The keys, values, and items Functions

Description: keys() Method

The method keys() returns a list of all the available keys in the dictionary.
Syntax

Following is the syntax for keys() method:

dict.keys()


Description: values() Method

The method values() returns a list of all the values available in a given dictionary.
Syntax

Following is the syntax for values() method:

dict.values()


Description items() Method

The method items() returns a list of dict's (key, value) tuple pairs
Syntax

Following is the syntax for items() method:

dict.items()

params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}

  1. params.keys()
  2. params.values()
  3. params.items()

  1. The keys method of a dictionary returns a list of all the keys. The list is not in the order inwhich the dictionary was defined (remember that elements in a dictionary are unordered),but it is a list.
  2. The values method returns a list of all the values. The list is in the same order as the listreturned by keys, so params.values()[n] == params[params.keys()[n]] for all values of n.
  3. The items method returns a list of tuples of the form (key, value). The list containsall the data in the dictionary.


List Comprehensions in buildConnectionString, Step by Step

params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
params.items()

  1. [k for k, v in params.items()]
  2. [v for k, v in params.items()]
  3. ["%s=%s" % (k, v) for k, v in params.items()]



  1. Note that you'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, you're ignoring the value of v and only including the value of k in the returned list, so this list comprehensionends up being equivalent to params.keys().
  2. Here you're doing the same thing, but ignoring the value of k, so this list comprehension ends up being equivalent to params.values().
  3. Combining the previous two examples with some simple string formatting, you 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.


A dictionary is mutable and is another container type that can store any number of Python objects, including other container types. Dictionaries consist of pairs (called items) of keys and their corresponding values.

Python dictionaries are also known as associative arrays or hash tables.

The general syntax of a dictionary is as follows:

dict = {'key1':'value1', 'key2':'value2', 'key3':'value3'}

dict.keys()

dict.values()

dict.items()

Mapping Types — dict

d[key] = value

Set d[key] to value.

del d[key]

Remove d[key] from d. Raises a KeyError if key is not in the map.

key in d

Return True if d has a key key, else False.

key not in d

Equivalent to not key in d.

iter(d)

Return an iterator over the keys of the dictionary. This is a shortcut for iter(d.keys()).

clear()

Remove all items from the dictionary.

copy()

Return a shallow copy of the dictionary.

classmethod fromkeys(seq[, value])

Create a new dictionary with keys from seq and values set to value.

fromkeys() is a class method that returns a new dictionary. value defaults to None.

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

items()

Return a new view of the dictionary’s items ((key, value) pairs). See the documentation of view objects.

keys()

Return a new view of the dictionary’s keys. See the documentation of view objects.

pop(key[, default])

If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.

popitem()

Remove and return an arbitrary (key, value) pair from the dictionary.

popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError.

setdefault(key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

update([other])

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).

values()

Return a new view of the dictionary’s values. See the documentation of view objects.