Help needed: optimizing dictionary creation/access

Peter Otten __peter__ at web.de
Sat Jun 19 04:18:20 EDT 2004


Pekka Niiranen wrote:

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

Untested:

def update(name, keyp, cost, unit, root):
    data = root.setdefault(name, {})
    data = data.setdefault(keyp, {})
    oldunit = data.get(cost, None)
    if oldunit:
        if unit > oldunit[0]:
            oldunit[:] = [unit, time.asctime()]
    else:
        data[cost] = [unit, time.asctime()]

    return root

You might consider using a single dictionary with (name, keyp, cost) tuples
as keys.

Peter




More information about the Python-list mailing list