Unknown quantity of items in configuration files using ConfigParser
To be honest I'm writing this question to try to clear up my mind in the process. If I can't figure it out, I'll post it (which happened). I would appreciate if someone could shed some light on how to approach this problem. I'm still noob enough to get overwhelmed by this kind of problems.
Let's say that in certain section of my config file I want to give the user the flexibility to add an arbitrary quantity of items, e.g.:
[mysection]
item1 = value1
item2 = value开发者_如何学运维2
item3 = value3
The items quantity can increase as the user wishes.
Which would be a nice way to parse this? At the moment I only came up with string manipulation by index of the list returned by ConfigParser's items method.
Hope I explained myself clear. Anyone has faced this before?
If I understand your question correctly, it seems to me that ConfigParser.items(section)
offers the functionality you need.
Perhaps it would help to know that you can call dict
on the resulting list of tuples? As in...
>>> l = [('name1', 'val1'), ('name2', 'val2')]
>>> d = dict(l)
>>> d
{'name2': 'val2', 'name1': 'val1'}
>>> d.items()
[('name2', 'val2'), ('name1', 'val1')]
>>> d.keys()
['name2', 'name1']
>>> d.values()
['val2', 'val1']
精彩评论