Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Python
extract to dictionaries
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Rhodri James, post: 3870575"] It would have. At the very least, it would have told us that you've missed a common idiom. Not posting code (or code snippets at least) makes it more likely that you'll be told to RTFM, you do realise! I'd be tempted to do it like this dict_of_dicts = {} current_dict = {} current_name = "dummy" f = open(filename) for line in f: # Do something to skip blank lines if line == '\n': continue # A normal 'key value' pair? if line.startswith(' '): # Yup. Split apart the key and value, # and add them to the current dictionary current_dict.update([line.split()]) elif line == 'end': # Wrap up what we've got and save the dictionary dict_of_dicts[current_name] = current_dict current_name = dummy current_dict = {} else: # New section. Really ought to whinge if # we haven't ended the old section. current_name = line.strip() current_dict = {} You can then pull the parameter sets you want out of dict_of_dicts (you can probably think of a more meaningful name for it, but I don't know the context you're working in). In real code I would use regular expressions rather than `startswith` and the equality because they cope more easily with tabs, newlines and other 'invisible' whitespace. [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Python
extract to dictionaries
Top