【问题标题】:Creating a dictionary of dictionaries from a text file从文本文件创建字典字典
【发布时间】:2017-06-05 20:08:47
【问题描述】:

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

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

但不知道怎么做。我做错了什么?

【问题讨论】:

    标签: python-3.x dictionary nested


    【解决方案1】:

    您没有更新字典键(或为每个级别创建新字典),试试这样?

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

    【讨论】:

      猜你喜欢
      • 2012-04-10
      • 2016-09-03
      • 2012-03-08
      • 1970-01-01
      • 1970-01-01
      • 2013-12-06
      • 2017-07-07
      • 1970-01-01
      相关资源
      最近更新 更多