[Tutor] Why dictionaries?

Kent Johnson kent37 at tds.net
Fri Jan 23 15:15:19 CET 2009


On Fri, Jan 23, 2009 at 8:57 AM, Vicent <vginer at gmail.com> wrote:
> A simple but maybe too wide question:
>
> When is it / isn't it useful to use dictionaries, in a Python program?
> I mean, what kind of tasks are they interesting for?

Lists are ordered, dicts are not
List indices are consecutive integers, dict keys can be any hashable
value (most often a number or string) and do not have to be
consecutive.

Dict lookup is fast, even for large dictionaries. List search is
sequential and gets slow for long lists. This can be a performance
killer, for example a common performance problem is code like this:
for item1 in very_long_list_1:
  if item1 in very_long_list_2:
    # do something with item1 that matches

This particular example is best solved with a set, not a dict, but the
performance of both is similar and sometimes a dict is the correct
solution. This will be significantly faster than the previous code:
list_2_items = set(very_long_list_2)
for item1 in very_long_list_1:
  if item1 in list_2_items:
    # do something with item1

Kent


More information about the Tutor mailing list