Skip to content

Instantly share code, notes, and snippets.

@bdiegel
Created June 30, 2014 17:01
Show Gist options
  • Save bdiegel/b7c6d063e2a1f1a74d87 to your computer and use it in GitHub Desktop.
Save bdiegel/b7c6d063e2a1f1a74d87 to your computer and use it in GitHub Desktop.
Python: convert types of values in dict that was creates by the csv.DictReader
"""
Originally wrote this to convert string values in dict created by csv.DictReader to int, float and bool.
Expects dictionary to be one-level (does not recurse into sub-dictionaries) and values to be type String.
"""
def convert_types(dict):
"""
Modifies types of values in dict in place
"""
def str2bool(value):
if value.lower() in ('true', 'false'):
return bool(value)
else:
raise ValueError
# try conversions in this order:
fxs = [ int, float, str2bool ]
for key, value in dict.iteritems():
for f in fxs:
try:
dict[key] = f(value)
break
except ValueError:
pass
return dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment