Help needed: optimizing dictionary creation/access

Pekka Niiranen pekka.niiranen at wlanmail.com
Sat Jun 19 03:22:02 EDT 2004


Hi there,

I have tree-like dictionary

data = {p_name: {p_keyp: {p_cost: [p_unit, t]}}}

which I update by creating nonexisting branches when necessary.
If the full branch already exists I update its 'p_unit' -value only if
it is greater than the presently stored item. See code below.

The use of method "has_key" with nested if -statements works,
but there MUST be a better way.

I was not able to take advantage of dictionary's
"setdefault" method (I got lost in nested setdefaults)
nor did I manage to find an elegant function to
"create the rest of the missing branch from
(this/any) point onwards", like:

try:
    data[p_name][p_keyp][p_cost] = [p_unit, t]
error:
    <create branch from missing key onwards>

Any ideas?


------------- code starts --------------
def update(p_name, p_keyp, p_cost, p_unit, data):
     t = time.asctime()
     if data.has_key(p_name):
         if data[p_name].has_key(p_keyp):
             if data[p_name][p_keyp].has_key(p_cost):
                 if p_unit > data[p_name][p_keyp][p_cost][0]:
                     data[p_name][p_keyp][p_cost] = [p_unit, t]
             else:
                 data[p_name][p_keyp][p_cost] = [p_unit, t]
         else:
             data[p_name][p_keyp] = {p_cost: [p_unit, t]}
     else:
         data[p_name] = {p_keyp: {p_cost: [p_unit, t]}}
     return data

------------- code stops --------------

-pekka-



More information about the Python-list mailing list