Skip to content

Instantly share code, notes, and snippets.

@un33k
Created August 28, 2014 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save un33k/bad2b68a5687f80fe94c to your computer and use it in GitHub Desktop.
Save un33k/bad2b68a5687f80fe94c to your computer and use it in GitHub Desktop.
string to integer AND integer to string conversions for Django Options
def choices_txt_2_int(choices, text, default=0):
"""
Returns the integer `value` of a text from a choice tuple or `default`.
"""
value = default
if isinstance(text, str):
try:
value = next(v for v, k in choices if k.lower()==text.lower())
except StopIteration:
pass
return value
def choices_int_2_txt(choices, integer, default='UNKNOWN'):
"""
Returns the text `value` of an integer from a choice tuple or `default`.
"""
try:
value = dict(choices)[integer]
except KeyError:
value = default
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment