Help needed: optimizing dictionary creation/access
Pekka Niiranen
pekka.niiranen at wlanmail.com
Sat Jun 19 05:57:18 EDT 2004
Hmm,
does not using tuple (name, keyp, cost) as key make access time linear?
-pekka-
Peter Otten wrote:
> 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