如何填充支持字典键多行值的python字典对象[关闭]

问题描述 投票:0回答:2
我正在使用python并从“ .txt”文件中读取内容,并在“键:值”对中填充python字典,如下所示。

示例文件的内容如下所示:

product: osName customers: verizon category: software class: CL1 file_location: /opt/test.txt Remarks: This is multi line data. This Line - 1 of remarks field. This Line - 2 of remarks field. This Line - 3 of remarks field.

我从文件读取并填充python字典的代码如下所示:

with open(txt_file) as f: for l in f: key_value = l.strip().split(':',1) txtdict[key_value[0].strip()] = key_value[1].strip()

上述解决方案只要键及其值仅在一行中,就可以正常工作。 

想知道如何为给定键填充可以支持多行值的python字典对象?

python dictionary
2个回答
1
投票
csv.reader模块准确且经过特定检查:

import csv with open('test.txt') as f: reader = csv.reader(f, delimiter=':', skipinitialspace=True) res = {} prev_key = '' for row in reader: if len(row) == 2: k, v = row res[k] = v prev_key = k else: res[prev_key] += f'\n{row[0]}' print(res)

输出:

{'Remarks': 'Line one\nLine 2 \nLine 3 of Remarks.', 'category': 'software', 'class': 'CL1', 'customers': 'verizon', 'file_location': '/opt/test.txt', 'product': 'osName'}


1
投票
在获取key_vale之后添加if语句

with open(txt_file) as f: for l in f: key_value = l.strip().split(':',1) if len(key_value) > 1: txtdict[key_value[0].strip()] = key_value[1].strip() else: txtdict[key_value[0].strip()] = None

© www.soinside.com 2019 - 2024. All rights reserved.