2017-06-05 87 views
0

我從看起來像這樣的一個文件中讀取數據創建字典的字典...從文本文件

ID; 34556 
hi; 8 
lo; 16 
threshold; 90 
ID; 54365 
hi; 0.03 
lo; 8 
threshold; 50 
...... 

到目前爲止,我有這個...

d = {} 
with open ('filename.txt', 'r') as f: 
    for l in f.readlines(): 
     split = l.split(';') 
     key = 'dictionary_key' 
     if 'id' in split[0]: 
      d.setdefault(key, {}).setdefault('id', split[1]) 
     if 'threshold' in split[0]: 
      d.setdefault(key, {}).setdefault('thresh', split[1]) 
     if 'hi' in split[0]: 
      d.setdefault(key, {}).setdefault('hi', split[1]) 
     if 'lo' in split[0]: 
      d.setdefault(key, {}).setdefault('lo', split[1]) 

但當我這樣做時,我的輸出只是這個...

{'dictionary_key': {'hi': '8', 'lo': '16', 'id': '34556', 'thresh': '90'}} 

我似乎創建了整個文件的嵌套字典。

本來我是想有ID的關鍵和其他一切落入嵌套的字典是這樣的...

{'34556': {'hi' : '8', 'lo' : '16', 'thresh' :90}} 

,但無法弄清楚如何。我究竟做錯了什麼?

回答

0

你沒有更新字典鍵(或爲每個關卡創建新的字典),嘗試這樣的事情?

import json 

str = """ 
ID; 34556 
hi; 8 
lo; 16 
threshold; 90 
ID; 54365 
hi; 0.03 
lo; 8 
threshold; 50 
""" 

data = {} 
id = None 
for line in str.split('\n'): 
    try: 
     key, value = line.split('; ') 
     if key == "ID": 
      id = value 
      data[id] = {} 
     elif id is not None: 
      data[id][key] = value 

    except Exception as e: 
     print(e, 'skipping line:', line) 

print(json.dumps(data, indent=4)) 

輸出:

{ 
    "34556": { 
     "lo": "16", 
     "hi": "8", 
     "threshold": "90" 
    }, 
    "54365": { 
     "lo": "8", 
     "hi": "0.03", 
     "threshold": "50 " 
    } 
}