2017-10-09 86 views
0

我有一個稍微不同的問題比以前提出的問題有關此主題。文本文件有以下內容python文件到字典

x1 x2 x3 gh3 tf2 
0.1 0.7 0.8 0.9 8.9 
y1 ft gt hh 
2 4 7 8 
. 
. 
. 

我想添加到字典,所以有鍵:值x1:0.1等等。

這是我現在有,它並沒有真正爲我工作

ned = {} 
nel =[] 
with open('test.dat', 'r') as f: 
    for line in f: 
     splitline= line.split() 
     print(splitline) 
     ned[int(splitline[0])] = ",".join(splitline[1:]) 

回答

0

隨着str.split()zip功能:

with open('test.dat', 'r') as f: 
    d = {} 
    for i,l in enumerate(f.read().splitlines()): 
     if not i % 2: 
      keys = l.split() 
     else: 
      d.update(zip(keys, l.split())) 

print(d) 

輸出:

{'x1': '0.1', 'y1': '2', 'tf2': '8.9', 'ft': '4', 'x3': '0.8', 'gh3': '0.9', 'hh': '8', 'x2': '0.7', 'gt': '7'} 
0
temp_dict = dict() 
with open("test.dat", 'r') as f: 
    lines = f.readlines() 
    for i in range(0, len(lines), 2): 
     keys = lines[i].split() 
     vals = lines[i + 1].split() 
     temp_dict.update(key: val for key, val in zip(keys, vals)) 
0

你可以試試這個:

data = [i.strip('\n').split() for i in open('filename.txt')] 
new_data = [{b[i]:b[i+1] for i in range(0, len(b), 2)} for b in zip(*data)] 
final_dict = {} 
for i in new_data: 
    final_dict.update(i) 

輸出:

{'x1': '0.1', 'ft': '4', 'gt': '7', 'gh3': '0.9', 'y1': '2', 'hh': '8', 'x2': '0.7', 'x3': '0.8',...} 
+0

這是最蟒蛇回答不錯,但也是不可讀的。這取決於你我喜歡的東西;) –

0
lines_read = [] 
with open("test.dat", "r") as f: 
    lines_read = f.readlines() 

key_line = [] 
value_line = [] 
out_dict = {} 
for i, line in enumerate(lines_read): 
    if i % 2 == 0: 
     key_line = line.strip().split() 
    else: 
     value_line = line.strip().split() 
     out_dict.update(dict(zip(key_line, value_line))) 

爲了簡潔,而且如果你不那麼在乎寫明確的代碼,你可以沒有列表的初始化:

with open("test.dat", "r") as f: 
    lines_read = f.readlines() 

out_dict = {} 
for i, line in enumerate(lines_read): 
    if i % 2 == 0: 
     key_line = line.strip().split() 
    else: 
     value_line = line.strip().split() 
     out_dict.update(dict(zip(key_line, value_line))) 
0

以下內容每次讀取兩行文件,並使用字典理解創建每2行字典更新my_dict有:

my_dict = {} 

with open('test.dat') as f_input: 
    for l1, l2 in zip(*[iter(f_input)] * 2): 
     my_dict.update({k: v for k, v in zip(l1.split(), l2.split())}) 

print(my_dict) 

給你:

{'gt': '7', 'ft': '4', 'gh3': '0.9', 'y1': '2', 'hh': '8', 'x2': '0.7', 'x3': '0.8', 'x1': '0.1', 'tf2': '8.9'} 

要將所有值轉換爲浮動,改變更新:

my_dict.update({k: float(v) for k, v in zip(l1.split(), l2.split())}) 

給你:

{'gh3': 0.9, 'tf2': 8.9, 'x3': 0.8, 'gt': 7.0, 'y1': 2.0, 'x1': 0.1, 'ft': 4.0, 'hh': 8.0, 'x2': 0.7}