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]
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With