Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding fast default aliases in Python

Tags:

python

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

aliases = {
            'United States': 'USA',
            'United Kingdom': 'UK',
            'Russia': 'RUS',
          }
if countryname in aliases: countryname = aliases[countryname]
like image 692
user132262 Avatar asked Jan 19 '26 06:01

user132262


2 Answers

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.

like image 112
mthurlin Avatar answered Jan 20 '26 20:01

mthurlin


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
like image 41
Ned Batchelder Avatar answered Jan 20 '26 19:01

Ned Batchelder