simple question on dictionary usage

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sun Oct 28 07:51:51 EDT 2007


Marc 'BlackJack' Rintsch>``s.startswith('E')`` is a little safer than
``s[0] == 'E'`` as the former returns `False` if `s` is empty while
the latter raises an `IndexError`.<

Thank you.
In this problem if there is an empty key in the record dict then maybe
it's better to raise an IndexError, because probably that's not a
normal condition. Sometimes less safe is more safe :-)

With few tests I have seen that (using Psyco) this is probably the
faster solution (and it's quite readable by a newbe too):

record2 = {}
for k in record:
  if k[0] == 'E':
    record2[k] = record[k]

Misteriously with Psyco it becomes faster than even the equivalent D
language solution (keys starting with "E" are about 5% of the total)
that is statically typed and generally very fast:

string[string] record2;
foreach(k, v; record)
  if (k[0] == 'E')
    record2[k] = v;

Bye,
bearophile




More information about the Python-list mailing list