simple question on dictionary usage
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Mon Oct 29 16:02:46 EDT 2007
Martin v. Löwis a écrit :
>>>egt = {}
>>>for key in record:
>>> if key.startswith('E'):
>>> egt[key] = record[key]
>>
>>I actually had come up with something like this, but thought it wasn't
>>quite as pythonish as it should be. It is certainly much more readable
>>to a neophyte to python.
>
>
> My recommendation: forget about the comprehension-based ones. It *is*
> Pythonic to have the code readable to a neophyte; there is no price to
> win for shortness or cuteness.
While I wholefully agree that readability is not something to
undervalue, I would not bash out list-comps (or generator-expressions,
as is the case below) based solutions for such a simple use-case.
Readability is not dumbness neither, and even if list-comps/generator
expression may be something new for most Python newbies, they *are* by
now the canonical, idiomatic Python way in this situation.
>
>>>egt = dict((k, v) for k, v in record.iteritems() if k.startswith('E'))
>>
>>This is what I was looking for. I thought I had seen something simular
>>to this in one of the tutorials I had read, but couldn't seem to find it.
>
>
> And you consider this readable? I find it way too complex.
As far as I'm concerned, I do find this solution much more readable than
it's more imperative counterpart.
More information about the Python-list
mailing list