Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
takes about 63 milliseconds, but invert_dict_fast manages the same task in just 20 milliseconds. A speed increase by a factor of three, in general, is not to be sneered at. Such performance gains, when you work on large amounts of data, are the norm, rather than the exception, for coding at higher abstraction levels. This is particularly true when you can use itertools rather than loops or list comprehensions, because you don't need to materialize some large list in memory at one time. Performance gain is an extra incentive for getting familiar with working at higher abstraction lev- els, a familiarity that has conceptual and productivity pluses, too. See Also Documentation on mapping types and itertools in the Library Reference and Python in a Nutshell; Chapter 19. 4.15 Associating Multiple Values with Each Key in a Dictionary Credit: Michael Chermside Problem You need a dictionary that maps each key to multiple values. Solution By nature, a dictionary is a one-to-one mapping, but it's not hard to make it one-to- many--in other words, to make one key map to multiple values. Your choice of one of two possible approaches depends on how you want to treat duplications in the set of values for a key. The following approach, based on using list s as the dict 's val- ues, allows such duplications: d1 = { } d1 .setdefault(key, [ ]).append(value) while an alternative approach, based on using sub- dict s as the dict 's values, auto- matically eliminates duplications of values: d2 = { } d2.setdefault(key, { })[value] = 1 In Python 2.4, the no-duplication approach can equivalently be coded: d3 = { } d3.setdefault(key, set( )).add(value) Discussion A normal dictionary performs a simple mapping of each key to one value. This rec- ipe shows three easy, efficient ways to achieve a mapping of each key to multiple 4.15 Associating Multiple Values with Each Key in a Dictionary | This is the Title of the Book, eMatter Edition Copyright © 2007 O'Reilly & Associates, Inc. All rights reserved. 173