Search code examples
pythoncurrency-formatting

PyCountry currency formatting woes for 'DE' alpha2 country code


I have a Python function which accepts an alpha2 country code and a price string, where the aim is to get the country's currency and use the currency.letter property of that currency to format the supplied price string using string interpolation.

The above works fine so far - yet it falls over when called with Germany as the country as follows:

>>> import pycountry
>>> country = pycountry.countries.get(alpha2='DE')
>>> currency = pycountry.currencies.get(numeric=country.numeric)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/pymodules/python2.6/pycountry/db.py", line 83, in get
    return self.indices[field][value]
KeyError: '276'
>>>

The pycountry.countries collection does not contain a currency with a numeric of 276 (Germany's numeric) - yet it does contain the Euro. Any ideas as to what the way around this may be?


Solution

  • Unfortunately, the country numeric code is NOT the same as the currency numeric. According to the ISO, "Where possible the 3 digit numeric code is the same as the numeric country code" - but this is obviously NOT possible for the Euro, which is shared by multiple countries.

    The numeric for the Euro is 978, not 276; apparently pycountry doesn't provide a mapping between country numerics and currency numerics. Here's a link to the raw tables (in XML or XLS format) so you can roll your own, if you so desire... http://www.currency-iso.org/en/home/tables/table-a1.html