[Csv] CSV module. DictReader uses string values instead of int

skip at pobox.com skip at pobox.com
Thu Jul 30 00:39:41 CEST 2009


    Guido> Using DictReader from the CSV module, my dictionary looks like this:

    Guido> mydict={'variable1': '0', 'variable2': '1', 'variable3': '0',  
    Guido> 'variable4': '1'}

    Guido> and I want it to look like this:

    Guido> mydict={'variable1': 0, 'variable2': 1, 'variable3': 0, 'variable4': 1}

Sure.  Just convert your dictionary's keys:

    for key in mydict:
        try:
            mydict[key] = int(mydict[key])
        except ValueError:
            # not an int
            pass

You can hide this from your application code by subclassing csv.DictReader
and overriding its next method (or __next__ method for Python 3.x):

    class MyDictReader(csv.DictReader):
        def next(self):
            d = csv.DictReader.next(self)
            for key in d:
                try:
                    d[key] = int(d[key])
                except ValueError:
                    # not an int
                    pass
            return d

-- 
Skip Montanaro - skip at pobox.com - http://www.smontanaro.net/
    That's more than a dress. That's an Audrey Hepburn movie. -- Jerry Maguire


More information about the Csv mailing list