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="Mike Kazantsev, post: 3870924"] You can use iterators to efficiently parse no-matter-how-large file. Following code depends on line breaks and 'end' statement rather than indentation. import itertools as it, operator as op, functools as ft from string import whitespace as spaces with open('test.src') as src: lines = it.ifilter(bool, it.imap(lambda x: x.strip(spaces), src)) sections = ( (lines.next(), dict(it.imap(str.split, lines))) for sep,lines in it.groupby(lines, key=lambda x: x == 'end') if not sep ) data = dict(sections) print data # { 'parameters2': {'key2': 'value2', 'key1': 'value1'}, # 'parameters1': {'key2': 'value2', 'key1': 'value1'} } To save namespace and make it a bit more unreadable you can write it as a one-liner: with open('test.src') as src: data = dict( (lines.next(), dict(it.imap(str.split, lines))) for sep,lines in it.groupby(it.ifilter(bool, it.imap(lambda x: x.strip(spaces), src)), key=lambda x: x == 'end') if not sep ) -- Mike Kazantsev // fraggod.net -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.11 (GNU/Linux) iEYEARECAAYFAkogabEACgkQASbOZpzyXnFOcwCgkxnm6pBNywpwWSeUs2md8dQA F4oAoPBNqAjf2gcgnCE48rscD0BbeFDV =rsy6 -----END PGP SIGNATURE----- [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Python
extract to dictionaries
Top