Help needed : Dictionary tricks in 2.2
Alex Martelli
aleax at aleax.it
Mon Jan 14 08:46:38 EST 2002
"pekka niiranen" <krissepu at vip.fi> wrote in message
news:3C429CF5.60700 at vip.fi...
...
> 2) The following code turns list (or tuple) into dictionary fast (without
doubles):
>
> >>> d = {}
> >>> l = ['a','b','c','b']
> >>> dummy = map(operator.setitem, [d]*len(l), l, [])
Ugly. Marginally better in 2.2
map(d.__setitem__, l, [])
but it's still pretty obscure.
> >>> d
> {'a': None, 'c': None, 'b': None}
>
> Q2: How can I modify the code to create dictionary with
> empty string -values instead of None's
>
> {'a': "", 'c': "", 'b': ""}
map(d.__setitem__, l, len(l)*[''])
but it's STILL a hack. Much clearer and more readable:
for item in l: d[item] = ''
and you'll likely never notice the performance-loss -- this
isn't going to be your application's bottleneck!
"Premature optimization is the root of all evil" (Knuth).
Target *clarity* first -- simplicity, readability, clean
and straightforward code. Time to squeeze out the last
drop of performance, *IF EVER*, comes once your program
is working, simple, and clean, and ONLY IF it's not fast
enough, and ONLY on those tiny areas of code that are in
fact part of a program's performance "bottleneck" (find
out by profiling -- intuition is misleading here).
Alex
More information about the Python-list
mailing list