Created
June 30, 2014 17:01
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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