Use the seqdict.py package:
What is it?
http://home.arcor.de/wolfgang.grafen/Python/Modules/AllOs/DOC/seqdict/
Downloads:
http://home.arcor.de/wolfgang.grafen/Python/Modules/seqdict/seqdict-0.3.zip
http://home.arcor.de/wolfgang.grafen/Python/Modules/AllOs/DOC/HTML/HTMLDoc.zip
http://home.arcor.de
Raymond Hettinger wrote:
>> from itertools import count, izip
>>
>> def dict2str(d, preferred_order = ['gid', 'type', 'parent', 'name']):
>> last = len(preferred_order)
>> rank = dict(izip(preferred_order, count()))
>> pairs = d.items()
>> pairs.sort(key=lambda (k,v): rank.get(k, (l
> from itertools import count, izip
>
> def dict2str(d, preferred_order = ['gid', 'type', 'parent', 'name']):
> last = len(preferred_order)
> rank = dict(izip(preferred_order, count()))
> pairs = d.items()
> pairs.sort(key=lambda (k,v): rank.get(k, (last, k, v)))
> return '{%s}'
[Kamilche]
> I have a code snippet here that prints a dict in an arbitrary order.
> (Certain keys first, with rest appearing in sorted order). I didn't
> want to subclass dict, that's error-prone, and overkill for my needs. I
> just need something that returns a value like dict.__str__, with a key
You can always use OrderedDict :
htttp://www.voidspace.org.uk/python/odict.html
from odict import OrderedDict
my_dict = OrderedDict(some_dict.keys())
keys = my_dict.keys()
keys.sort()
my_dict.setkeys(keys)
print my_dict
Of course if your ordering requirement was *that* trivial, you could do
"Kamilche" <[EMAIL PROTECTED]> writes:
> I have a code snippet here that prints a dict in an arbitrary order.
> (Certain keys first, with rest appearing in sorted order). I didn't
> want to subclass dict, that's error-prone, and overkill for my needs. I
> just need something that returns a value l
I have a code snippet here that prints a dict in an arbitrary order.
(Certain keys first, with rest appearing in sorted order). I didn't
want to subclass dict, that's error-prone, and overkill for my needs. I
just need something that returns a value like dict.__str__, with a key
ordering I specify.