2016-09-18 95 views
1

我有类似的文件下面:从一个文件中的一个关键追加多个值

t_air_sens1 
laten 
t_air_sens1 
periodic 
t_air_air 
laten 
t_air_air 
periodic 
... 
... 

我想要一本字典,以指定laten和这些值周期性到和t_air_sens1每个键等最后的结果一定是类似下面:

{ 
    "t_air_sens1": [laten,periodic] 
    "t_air_air": [laten,periodic] 
    ... 
    ... 
} 

我确实写了下面的代码:

prop_dict = {} 
with open('file.pl') as f, open('result.pl', 'w') as procode: 
    for line in f: 
     if line[0] in prop_dict: 
      prop_dict[line[0]].append(line[1]) 
     else: 
      prop_dict[line[0]] = [line[1]] 
     #will write the values in "result.pl" 

但结果我得到的,当我尝试打印字典是类似下面:

{'p': ['e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e'], 
't': ['_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', 
     '_', '_', '_', '_', '_', '_', '_', '_', '_'], 
'l': ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']} 

我能做些什么来解决这个问题?我如何需要查询才能获得正确的结果?

回答

3

line[0]line[1]是字符串中的单个字符,而不是当前行和下一行。

文件对象是迭代器;该for循环会得到新的生产线,从它每一次迭代,但你也可以使用next() function拉在另一条线使用了这点时间读两行:

prop_dict = {} 
with open('file.pl') as f: 
    for key in f: 
     key = key.rstrip('\n') 
     # get the next line as the value 
     value = next(f).rstrip('\n') 
     prop_dict.setdefault(key, []).append(value) 

我也用dict.setdefault()插入一个空列出字典中缺失的任何键。像prop_dict[key]一样,它会返回字典中的当前值,但如果没有这样的密钥,则在返回空列表之前首先执行prop_dict[key] = []

上述工作原理是由于循环迭代时,for循环逐行读取一行,基本上在内部使用next()。在循环中调用next(f)只需额外添加一行,并且for循环再次从那里继续,因此您在读取属性名称(key)和属性值(value)之间交替。

请注意,如果通过读取for循环中的最后一行来达到文件的末尾,则next()会引发StopIteration异常;这会表明你的文件没有偶数行。如果这不是错误,则可以指定默认值:next(f, '')将返回空字符串''(如果文件已用尽)。

相关问题