tags:

views:

86

answers:

4

Is there a faster way to do this for much larger dicts?

aliases = {
            'United States': 'USA',
            'United Kingdom': 'UK',
            'Russia': 'RUS',
          }
if countryname in aliases: countryname = aliases[countryname]
+1  A: 

Accessing with .get could be faster than checking and assigning in variable

aliases.get(countryname)

And if countryname is not exists in aliases it will return None.

S.Mark
`.get()` can be given a default argument, so `aliases.get(countryname, countryname)` will do the trick concerning the "will return None" problem.
balpha
good idea, thanks for follow up.
S.Mark
+2  A: 

If your list fits in memory, dicts are the fastest way to go. As S.Mark points out, you are doing two lookups where one will do, either with:

countryname = aliases.get(countryname, countryname)

(which will leave countryname unchanged if it isn't in the dictionary), or:

try:
    countryname = aliases[countryname]
except KeyError:
    pass
Ned Batchelder
+6  A: 

Your solution is fine, as "in" is 0(1) for dictionaries.

You could do something like this to save some typing:

countryname = aliases.get(countryname, countryname)

(But I find your code a lot easier to read than that)

When it comes to speed, what solution is best would depend on if there will be a majority of "hits" or "misses". But that would probably be in the nanosecond range when it comes to difference.

truppo
Upped because of the part noting speed depends on the number of hits or misses
Mark
A: 

If your dictionary is very large and you expect many of your checks not to find a match, then you might want to consider a Bloom filter or one of it's derivatives and allow false positives.

Alternatively, because your keys can be sorted (and/or have a derived values), you could implement a bisection or other root-finding algorithm.

First, I'd figure out exactly how Python implements dictionary look-ups, so you are not just re-inventing the wheel.

Also, a pure-Python implementation of these could be quite slow if it involves a lot of iteration. Consider Cython, Numpy, or F2Py to get truly optimized.

(if you are dealing with just country names, then I don't think you are dealing with mappings large enough to warrant any of my suggestions), but if you are looking at doing some kind of spell-check implementation, then..

Good luck.

bpowah