使用理解从一个.tsv创建两个词典

时间:2015-03-31 16:29:08

标签: python python-2.7 dictionary list-comprehension

我有一个.tsv由一个键和两个值组成。我想创建两个字典,一个从键到映射到文件中每一行的第一个值,另一个映射从键到第二个值。我可以这样做:

v1Dict = {key: v1 for (key,v1,v2) in (line.split("\t") for line in (open (myinputfile)))}
v2Dict = {key: v2 for (key,v1,v2) in (line.split("\t") for line in (open (myinputfile)))}

但是,它读取/解析整个文件两次显然效率低下。

或者,我可以这样做:

v1Dict = {}
v2Dict = {}
for (key,v1,v2) in (line.split("\t") for line in (open (myinputfile))):
    v1Dict[key]=v1
    v2Dict[key]=v2

这是最好的"这样做的方法?

1 个答案:

答案 0 :(得分:0)

You can use with:

v1Dict = {}
v2Dict = {}
with open(myinputfile) as f:
    for(key, v1, v2) in [line.split("\t") for line in f]:
        v1Dict[key] = v1
        v2Dict[key] = v2

或者,你可以把它变成一个单行:

f = open(myinputfile);v1Dict,v2Dict=[{key: v1 for (key,v1,v2) in (line.split("\t") for line in f)}, {key: v2 for (key,v1,v2) in (line.split("\t") for line in f)}]

有关使用with的更多信息,请查看here