Skip to content

Commit 0bb4bdf

Browse files
authored
bpo-35864: Replace OrderedDict with regular dict in namedtuple() (#11708)
* Change from OrderedDict to a regular dict * Add blurb
1 parent 0897e0c commit 0bb4bdf

File tree

4 files changed

+21
-2
lines changed

4 files changed

+21
-2
lines changed

Doc/library/collections.rst

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -894,11 +894,18 @@ field names, the method and attribute names start with an underscore.
894894

895895
>>> p = Point(x=11, y=22)
896896
>>> p._asdict()
897-
OrderedDict([('x', 11), ('y', 22)])
897+
{'x': 11, 'y': 22}
898898

899899
.. versionchanged:: 3.1
900900
Returns an :class:`OrderedDict` instead of a regular :class:`dict`.
901901

902+
.. versionchanged:: 3.8
903+
Returns a regular :class:`dict` instead of an :class:`OrderedDict`.
904+
As of Python 3.7, regular dicts are guaranteed to be ordered. If the
905+
extra features of :class:`OrderedDict` are required, the suggested
906+
remediation is to cast the result to the desired type:
907+
``OrderedDict(nt._asdict())``.
908+
902909
.. method:: somenamedtuple._replace(**kwargs)
903910

904911
Return a new instance of the named tuple replacing specified fields with new

Doc/whatsnew/3.8.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,14 @@ New Modules
125125
Improved Modules
126126
================
127127

128+
* The :meth:`_asdict()` method for :func:`collections.namedtuple` now returns
129+
a :class:`dict` instead of a :class:`collections.OrderedDict`. This works because
130+
regular dicts have guaranteed ordering in since Python 3.7. If the extra
131+
features of :class:`OrderedDict` are required, the suggested remediation is
132+
to cast the result to the desired type: ``OrderedDict(nt._asdict())``.
133+
(Contributed by Raymond Hettinger in :issue:`35864`.)
134+
135+
128136
asyncio
129137
-------
130138

Lib/collections/__init__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -426,9 +426,11 @@ def __repr__(self):
426426
'Return a nicely formatted representation string'
427427
return self.__class__.__name__ + repr_fmt % self
428428

429+
_dict, _zip = dict, zip
430+
429431
def _asdict(self):
430432
'Return a new OrderedDict which maps field names to their values.'
431-
return OrderedDict(zip(self._fields, self))
433+
return _dict(_zip(self._fields, self))
432434

433435
def __getnewargs__(self):
434436
'Return self as a plain tuple. Used by copy and pickle.'
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
The _asdict() method for collections.namedtuple now returns a regular dict
2+
instead of an OrderedDict.

0 commit comments

Comments
 (0)