Search code examples
pythondictionarypython-itertools

Pythonic / itertools way to go through a dict?


def reportCSV(t):
    ret = ''
    for ev in t:
        for p in t[ev]:
            for w in t[ev][p]:
                ret += ','.join((ev, p, w, t[ev][p][w])) + '\n'
    return ret

What is a more pythonic way to do this, e.g. using itertools or the like?

In this case I'm just writing it out to a CSV file. t is a dict t[ev] is a dict t[ev][p] is a dict t[ev][p][w] is a float

I'm not sure how I'd use itertools.product in this case.


Solution

  • What you have could be rewritten as:

    def reportCSV(t):
        result = []
        for t_key, t_value in t.iteritems():
            for p_key, p_value in t_value.iteritems():
                for w_key, w_value in p_value.iteritems():
                    row_data = t_key, p_key, w_key, w_value
                    result.append(','.join(row_data))
        return '\n'.join(result)
    

    This will be faster since it joins strings together instead of performing a number of concatenations, and more efficient because it uses iteritems() which removes the need to do any extra dictionary lookups or create intermediary lists.