FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

recommend OrderedDict for this FAQ (closes #19805) · python/cpython@b152e17 · GitHub

Repository navigation

Commit b152e17

Browse files
committed
recommend OrderedDict for this FAQ (closes #19805)
1 parent 0ee22bf commit b152e17

1 file changed

Lines changed: 3 additions & 27 deletions

File tree

‎Doc/faq/programming.rst‎

Lines changed: 3 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1193,34 +1193,10 @@ that final assignment still results in an error, because tuples are immutable.
11931193
Dictionaries
11941194
============
11951195

1196-
How can I get a dictionary to display its keys in a consistent order?
1197-
---------------------------------------------------------------------
1198-
1199-
You can't. Dictionaries store their keys in an unpredictable order, so the
1200-
display order of a dictionary's elements will be similarly unpredictable.
1201-
1202-
This can be frustrating if you want to save a printable version to a file, make
1203-
some changes and then compare it with some other printed dictionary. In this
1204-
case, use the ``pprint`` module to pretty-print the dictionary; the items will
1205-
be presented in order sorted by the key.
1206-
1207-
A more complicated solution is to subclass ``dict`` to create a
1208-
``SortedDict`` class that prints itself in a predictable order. Here's one
1209-
simpleminded implementation of such a class::
1210-
1211-
class SortedDict(dict):
1212-
def __repr__(self):
1213-
keys = sorted(self.keys())
1214-
result = ("{!r}: {!r}".format(k, self[k]) for k in keys)
1215-
return "{{{}}}".format(", ".join(result))
1216-
1217-
__str__ = __repr__
1218-
1219-
This will work for many common situations you might encounter, though it's far
1220-
from a perfect solution. The largest flaw is that if some values in the
1221-
dictionary are also dictionaries, their values won't be presented in any
1222-
particular order.
1196+
How can I get a dictionary to store and display its keys in a consistent order?
1197+
-------------------------------------------------------------------------------
12231198

1199+
Use :class:`collections.OrderedDict`.
12241200

12251201
I want to do a complicated sort: can you do a Schwartzian Transform in Python?
12261202
------------------------------------------------------------------------------

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL