从文本文件创建字典字典

时间:2017-06-05 20:08:47

标签: python-3.x dictionary nested

我正在从一个看起来像这样的文件中读取数据......

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

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

1 个答案:

答案 0 :(得分: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 "
    }
}