Pythonic infinite for loop?

Peter Otten __peter__ at
Fri Apr 15 05:32:31 EDT 2011

Chris Angelico wrote:

> On Fri, Apr 15, 2011 at 6:25 PM, Peter Otten <__peter__ at> wrote:
>> The initial data structure seems less than ideal. You might be able to
>> replace it with a dictionary like
>> {"Keyword": [value_for_keyword_1, value_for_keyword_2, ...]}
>> if you try hard enough.
> The initial data structure comes from a CSV file, and is not under my
> control.
> ChrisA

Here's some code that might give you an idea. You can ignore the chunk 
before 'import csv'; it is there to make the demo self-contained.

from contextlib import contextmanager

def open(filename):
    assert filename == "example.csv"
    from StringIO import StringIO
    yield StringIO("""\

import csv
import re

def parse_name(s):
    name, index = re.match(r"(.+?)(\d+)$", s).groups()
    return name, int(index)-1

with open("example.csv") as instream:
    rows = csv.reader(instream)
    header = next(rows)
    dct = {}
    appends = []
    for h in header:
        name, index = parse_name(h)
        outer = dct.setdefault(name, {})
        inner = outer.setdefault(index, [])
    for row in rows:
        for value, append in zip(row, appends):
print dct

More information about the Python-list mailing list