从文本文件

问题描述:

我从看起来像这样的一个文件中读取数据创建字典的字典...从文本文件

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}} 

,但无法弄清楚如何。我究竟做错了什么?

你没有更新字典键(或为每个关卡创建新的字典),尝试这样的事情?

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 " 
    } 
}