simple question on dictionary usage

"Martin v. Löwis" martin at v.loewis.de
Sun Oct 28 19:27:00 CET 2007


>> 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.

>> 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.

> Ah!  Now this is one solution I can get my teeth into.  If its not obvious,
> I'm a recovering perl programmer.

Ok, I now see why you can appreciate the comprehension-based one :-)

Again, much of Python's strength comes from it being readable. Simple
is better than complex, and sparse is better than dense, and readability
counts (import this).

Regards,
Martin



More information about the Python-list mailing list