acting on items passed to a method via a dictiomary

Ville Vainio ville at spammers.com
Fri Oct 15 14:33:41 EDT 2004


>>>>> "Donnal" == Donnal Walter <donnal at donnal.net> writes:

    Donnal> if 'something' in items:
    Donnal>     value = items['something']
    Donnal>     # now do something with value
    Donnal> if 'another' in items:
    Donnal>     value = items['another']
    Donnal>     # do something else with value

    Donnal> overridden in subclasses. The approach described above
    Donnal> works ok, so I suppose I should leave well enough alone,
    Donnal> but I have this nagging feeling that Python has a way to
    Donnal> do this more simply or more elegantly. Any suggestion?

The code is quite ok - you might avoid the repetition of 'something'
by using

a.get(k[, x])   

# a[k] if k in a, else x

If you feel 'clever' and don't care about performance (no, I didn't
benchmark this):

-----
def dictget(d, key):
    if key in d: 
        yield d[key]
    return

d = { 'spam' : 1, 'eggs' : 67 }

for value in dictget(d,'spam'):
    print value

for value in dictget(d,'larch'):
    print value + 999   # never printed


for value in dictget(d,'eggs'):
    print value + 2
-----

Well well, that's almost cookbook material even if I say so myself... ;-)

-- 
Ville Vainio   http://tinyurl.com/2prnb



More information about the Python-list mailing list