Dictionaries and loops

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Mon Sep 8 09:55:52 EDT 2008


Few solutions, not much tested:

data = """{None: ['User-ID', 'Count']}
{None: ['576460847178667334', '1']}
{None: ['576460847178632334', '8']}"""

lines = iter(data.splitlines())
lines.next()

identity_table = "".join(map(chr, xrange(256)))
result = {}
for line in lines:
    parts = line.translate(identity_table, "'[]{},").split()
    key, val = map(int, parts[1:])
    assert key not in result
    result[key] = val
print result

(With Python 3 finally that identity_table can be replaced by None)

# --------------------------------------

import re

patt = re.compile(r"(\d+).+?(\d+)")

lines = iter(data.splitlines())
lines.next()

result = {}
for line in lines:
    key, val = map(int, patt.search(line).groups())
    assert key not in result
    result[key] = val
print result

# --------------------------------------

from itertools import groupby

lines = iter(data.splitlines())
lines.next()

result = {}
for line in lines:
    key, val = (int("".join(g)) for h,g in groupby(line,
key=str.isdigit) if h)
    assert key not in result
    result[key] = val
print result

Bye,
bearophile



More information about the Python-list mailing list