gather information from various files efficiently

Keith Dart kdart at kdart.com
Tue Dec 14 10:30:51 CET 2004


Klaus Neuner wrote:
> Hello,
> 
> I need to gather information that is contained in various files.
> 
> Like so:
> 
> file1:
> =====================
> foo : 1 2
> bar : 2 4
> baz : 3
> =====================
> 
> file2:
> =====================
> foo : 5
> bar : 6
> baz : 7
> =====================
> 
> file3:
> =====================
> foo : 4 18
> bar : 8
> =====================
> 
> 
> The straightforward way to solve this problem is to create a
> dictionary. Like so:
> 
> 
> [...]
> 
> a, b = get_information(line)
> if a in dict.keys():
>     dict[a].append(b)
> else:
>     dict[a] = [b]

Aye...

the dict.keys() line creates a temporary list, and then the 'in' does a 
linear search of the list. Better would be:

try:
     dict[a].append(b)
except KeyError:
     dict[a] = [b]

since you expect the key to be there most of the time, this method is 
most efficient. You optomistically get the dictionary entry, and on the 
exceptional case where it doesn't yet exist you add it.






-- 
                            \/ \/
                            (O O)
-- --------------------oOOo~(_)~oOOo----------------------------------------
Keith Dart <kdart at kdart.com>
public key: ID: F3D288E4
============================================================================



More information about the Python-list mailing list