文本文件嵌套在一个 Python 字典中有多个变量



我有一个格式化如下的文本文件:

[one]
A = color
B = Petals
C = Junk
[two]
Z = 10
A = freq
corner = yes
[three]
D = code
status = 45

我正在尝试将此文件读入嵌套字典,使其如下所示:

{'one':{'A':'color','B':'Petals','C':'Junk'},
{'two':{'Z':'10','A':'freq':'corner':'yes'},
{'three':{'D':'code','status':'45'}}

我试过了

import re
ini_sections = []
ini_dict = {}
x = 0
with open(path,'r') as f:
for line in f:
re_found = re.findall('[(.*?)]',line)
re_found = ''.join(re_found)
ini_sections.append(re_found)
try:
if re_found:
next_line = next(f)
while re.findall('=',next_line):
key,value = next_line.rstrip('n').split('=')
ini_dict.update({ini_sections[x]:{key.strip():value.strip()}})
next_line = next(f)
x +=1
except StopIteration:
print("EOF!")

输出:

for key, value in ini_dict.items():
print(key, value)
>>>one {'C':'Junk'}
two {'corner':'yes'}
three {'status':'45'}

但字典中只剩下最后一项。 不知道为什么会这样。

您不需要单独的ini_sections(您可以创建它们,但在打印时甚至不会迭代它们中的每一个(。创建一个ini_dict,它将包含三个主键onetwothree,每个键的值为dict。当前字典的名称将为re_found;仅更新循环中的内容

您的原始代码,在这里和那里更改:

import re
import pprint
ini_dict = {}
x = 0
with open('test.cfg','r') as f:
for line in f:
re_found = re.findall('[(.*?)]',line)
re_found = ''.join(re_found)
ini_dict[re_found] = dict()
try:
if re_found:
next_line = next(f)
while re.findall('=',next_line):
key,value = next_line.rstrip('n').split('=')
ini_dict[re_found][key.strip()] = value.strip()
next_line = next(f)
except StopIteration:
print("EOF!")
pp = pprint.PrettyPrinter()
pp.pprint (ini_dict)

结果(缩进由漂亮印刷提供(:

EOF!
{'one': {'A': 'color', 'B': 'Petals', 'C': 'Junk'},
'three': {'D': 'code', 'status': '45'},
'two': {'A': 'freq', 'Z': '10', 'corner': 'yes'}}

最新更新