Pythonic infinite for loop?

Peter Otten __peter__ at web.de
Fri Apr 15 11:32:31 CEST 2011


Chris Angelico wrote:

> On Fri, Apr 15, 2011 at 6:25 PM, Peter Otten <__peter__ at web.de> 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

@contextmanager
def open(filename):
    assert filename == "example.csv"
    from StringIO import StringIO
    yield StringIO("""\
beta3,alpha1,alpha2,beta1,beta2
b31,a11,a21,b11,b21
b32,a12,a22,b12,b22
b33,a13,a23,b13,b23
b34,a14,a24,b14,b24
""")

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, [])
        appends.append(inner.append)
    for row in rows:
        for value, append in zip(row, appends):
            append(value)
print dct




More information about the Python-list mailing list