| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -1193,34 +1193,10 @@ that final assignment still results in an error, because tuples are immutable. | |||
| 1193 | 1193 | Dictionaries | |
| 1194 | 1194 | ============ | |
| 1195 | 1195 | ||
| 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 | + ------------------------------------------------------------------------------- | ||
| 1223 | 1198 | ||
| 1199 | + Use :class:`collections.OrderedDict`. | ||
| 1224 | 1200 | ||
| 1225 | 1201 | I want to do a complicated sort: can you do a Schwartzian Transform in Python? | |
| 1226 | 1202 | ------------------------------------------------------------------------------ | |
| Back | FazBrowse Home | New Git URL |
0 commit comments