Ordering in the printout of a dictionary
John Gordon
gordon at panix.com
Mon Mar 17 22:56:21 EDT 2014
In <mailman.8231.1395103693.18130.python-list at python.org> Chris Angelico <rosuav at gmail.com> writes:
> > Is there a way to force a certain ordering of the printout or else
> > somehow manage to get at least a certain stable ordering of the
> > printout (i.e. input and output are identical)?
> Yes; instead of simply printing it out (which calls repr()),
> explicitly iterate over it, like this:
> def display(d):
> return '{'+','.join('%r: %r'%(key,d[key]) for key in sorted(d))+'}'
You could also use the OrderedDict type, which is subclass of dict that
preserves insertion order.
--
John Gordon Imagine what it must be like for a real medical doctor to
gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'.
More information about the Python-list
mailing list