python - Reading from file using dict comprehensions -
i regularly need read data (typically tab-separated value) files , convert them dicts. need map 1 of columns another, there processing of values (such stripping whitespace) well. i've been trying come dict comprehension pattern that, keep running small nuisances keep me implementing succinct , understandable way consistently. , have feeling there better way.
so here (some of the) ways have tried, , went wrong:
open(path) f: return {line.split("\t")[0].strip(): line.split("\t")[1].strip() line in f}
this end using. allows me modify key , value in place, , work on of columns (e.g. if wanted map values third first column). obvious problem duplication of line.split()
part. there way bind line.split("\t")
temporary variable, or unpack values directly variables?
open(path) f: return dict(line.split("\t")[:2] line in f)
i came this. works nicely simple case (just mapping first second column, without processing), doesn't generalize other cases. additional processing hard , columns used have adjacent. not strict dict comprehension, , can't turned 1 because using slices.
d = dict() line in open(path): d.update({line.split("\t")[0]: line.split("\t")[1]}) return d
of course, create dict first , update every line. have create dict , return separately, , code duplication still there.
i have played around nested dict comprehensions , unpacking splitted line variables, ran different problems that.
you can sort of that, putting around f
:
def tabsplit(file_object): line in file_object: yield line.split("\t")
and later:
with open(path) f: return {left.strip(): right.strip() left, right, *rest in tabsplit(f)}
Comments
Post a Comment