问题
I have a text file that is formatted as follows:
[one]
A = color
B = Petals
C = Junk
[two]
Z = 10
A = freq
corner = yes
[three]
D = code
status = 45
I'm trying to read this file into a nested dictionary so that it looks like this:
{'one':{'A':'color','B':'Petals','C':'Junk'},
{'two':{'Z':'10','A':'freq':'corner':'yes'},
{'three':{'D':'code','status':'45'}}
I tried
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!")
Output:
for key, value in ini_dict.items():
print(key, value)
>>>one {'C':'Junk'}
two {'corner':'yes'}
three {'status':'45'}
But only the last items remain in the dictionary. Not sure why that is.
回答1:
You don't need a separate ini_sections
(you create them but you don't even iterate over each of them while printing). Create one ini_dict
, which will contain the three main keys one
, two
, and three
, each one with a value of a dict
. The current dict's name will be re_found
; update only that inside your loop.
Your original code, changed here and there:
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)
Result (indentation comes courtesy of prettyprint):
EOF!
{'one': {'A': 'color', 'B': 'Petals', 'C': 'Junk'},
'three': {'D': 'code', 'status': '45'},
'two': {'A': 'freq', 'Z': '10', 'corner': 'yes'}}
来源:https://stackoverflow.com/questions/59831811/text-file-into-a-nested-python-dictionary-more-than-one-variable