【问题标题】:Python dictionary based on input file基于输入文件的 Python 字典
【发布时间】:2021-06-02 11:58:12
【问题描述】:

我正在尝试使用如下输入文件数据结构创建一个字典对象,如下所示,在转换期间,内部对象正在被复制。任何建议需要什么修复来实现期望输出

输入文件数据:/home/file1.txt

[student1]
fname       : Harry
lname       : Hoit
age         : 22

[Student2]
fname       : Adam
lname       : Re
age         : 25

预期输出:

{'Student1' : {'fname' : 'Harry', 'lname' : 'Hoit', 'Age' : 22},
'Student2' : {'fname' : 'Adam', 'lname' : 'Re', 'Age' : 25}}
def dict_val():
    out = {}
    inn = {}
    path= '/home/file1.txt'
    with open(path, 'r') as f:
        for row in f:
            row = row.strip()
            if row.startswith("["):
                i = row[1:-1]
                # inn.clear() ## tried to clean the inner loop during second but its not correct
            else:
                if len(row) < 2:
                    pass
                else:
                    key, value = row.split('=')
                    inn[key.strip()] = value.strip()
                    out[i] = inn
    return out

print(dict_val())

当前输出:在第二次迭代中重复

{'student1': {'fname': 'Adam', 'lname': 'Re', 'age': '25'}, 
 'Student2': {'fname': 'Adam', 'lname': 'Re', 'age': '25'}}

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    只需一点点改变,你就会得到它。你已经很接近了。

    修改包括检查空行。当该行为空时,将inn数据写入out,然后清空inn

    def dict_val():
        out = {}
        inn = {}
        path= 'file.txt'
    
        with open(path, 'r') as f:
            for row in f:
                row = row.strip()
                if row.startswith("["):
                    i = row[1:-1]
                    continue
                
                # when the line is empty, write it to OUT dictionary
                # reset INN dictionary
                if len(row.strip()) == 0:
                    if len(inn) > 0:
                        out[i] = inn
                    inn = {}
                    continue
                
                key, value = row.split(':')
                inn[key.strip()] = value.strip()
    
        # if last line of the file is not an empty line and
        # the file reading is done, you can check if INN still
        # has data. If it does, write it out to OUT
        if len(inn) > 0:
           out[i] = inn
    
        return out
    
    print(dict_val())
    

    【讨论】:

      【解决方案2】:

      当您执行out[i] = inn 时,您将引用/指针复制到 inn 字典。这意味着当 inn 字典在循环的后期更新时,你的 out[1] 和 out[2] 指向同一个东西。

      要解决这个问题,您可以创建 inn 对象的深拷贝。

      参考:Nested dictionaries copy() or deepcopy()?

      【讨论】:

        【解决方案3】:

        我会一次性使用嵌套字典,因为你没有深入。

        def dict_val(file):
            inn = {}
            for row in open(file, 'r'):
                row = row.strip()
                if row.startswith("["):
                    i = row[1:-1]
                elif len(row) > 2:
                    key, value = row.split(':')
                    inn[i][key.strip()] = value.strip()
            return inn
        
        print(dict_val('/home/file1.txt'))
        

        【讨论】:

          猜你喜欢
          • 2018-11-16
          • 2021-07-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-10
          • 1970-01-01
          相关资源
          最近更新 更多