Check for dict key existence, and modify it in one step.

rodrigo rodrigo.cr at gmail.com
Tue Aug 28 10:36:50 EDT 2007


Im using this construct a lot:

if dict.has_key(whatever):
    dict[whatever] += delta
else:
    dict[whatever] = 1

sometimes even nested:

if dict.has_key(whatever):
    if dict[whatever].has_key(someother):
        dict[whatever][someother] += delta
    else:
        dict[whatever][someother] = 1
else:
    dict[whatever]={}
    dict[whatever][someother] = 1

there must be a more compact, readable and less redundant way to do
this, no?

Thanks,

Rodrigo




More information about the Python-list mailing list