Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!news.glorb.com!news.linkpendium.com!news.linkpendium.com!panix!gordon From: John Gordon Newsgroups: comp.lang.python Subject: Re: Ordering in the printout of a dictionary Date: Tue, 18 Mar 2014 02:56:21 +0000 (UTC) Organization: PANIX Public Access Internet and UNIX, NYC Lines: 19 Message-ID: References: NNTP-Posting-Host: panix3.panix.com X-Trace: reader1.panix.com 1395111381 11128 166.84.1.3 (18 Mar 2014 02:56:21 GMT) X-Complaints-To: abuse@panix.com NNTP-Posting-Date: Tue, 18 Mar 2014 02:56:21 +0000 (UTC) User-Agent: nn/6.7.3 Xref: csiph.com comp.lang.python:68476 In Chris Angelico 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@panix.com watch 'House', or a real serial killer to watch 'Dexter'.