Home > database >  Optimization: How to read csv data in python to a dict with converting strings in their booleans?
Optimization: How to read csv data in python to a dict with converting strings in their booleans?

Time:10-14

This is an optimization question as I have a working code that reads data from a csv file and created a python dictionary from it with strings like True or false converted to their boolean counterpart:

def _load_metadata(path):
    """Loads the metadata from the given file and converts boolean strings to booleans."""
    filedict = {}
    with open(path) as csvfile:
        reader = csv.DictReader(csvfile, delimiter=",")
        for row in reader:
            newrow = {}
            for key, value in dict(row).items():
                if value.lower() == "false":
                    newrow[key] = False
                elif value.lower() == "true":
                    newrow[key] = True
                else:
                    newrow[key] = value
            filedict[row["name"]]= newrow 
    return filedict

But I wonder if there is a better/more pythonic way to handle this?

CodePudding user response:

Soluthon from my comment:

def _load_metadata(path):
    """Loads the metadata from the given file and converts boolean strings to booleans."""
    filedict = {}
    with open(path) as csvfile:
        reader = csv.DictReader(csvfile, delimiter=",")
        for row in reader:
            newrow = {}
            for key, value in dict(row).items():
                # if value.lower() not in {"false": False, "true": True} it returns value as default
                newrow[key] = {"false": False, "true": True}.get(value.lower(), value)

            filedict[row["name"]]= newrow
    return filedict

Here the doc about this dicts .get() method

  • Related