[New-bugs-announce] [issue31992] Make iteration over dict_items yield namedtuples
Richard Neumann
report at bugs.python.org
Thu Nov 9 11:24:13 EST 2017
New submission from Richard Neumann <r.neumann at homeinfo.de>:
Currently, iterating over dict_items will yield plain tuples, where the first item will be the key and the second item will be the respective value.
This has some disadvantages when e.g. sorting dict items by value and key:
def sort_by_value_len(dictionary):
return sorted(dictionary.items(), key=lambda item: (len(item[1]), item[0]))
I find this index accessing extremely unelegant and unnecessarily hard to read.
If dict_items would instead yield namedtuples like
DictItem = namedtuple('DictItem', ('key', 'value'))
this would make constructs like
def sort_by_value_len(dictionary):
return sorted(dictionary.items(), key=lambda item: (len(item.value), item.key))
possible and increase code clarity a lot.
Also, namedtuples mimic the behaviour of plain tuples regarding unpacking and index accessing, so that backward-compatipility should exist.
----------
components: Library (Lib)
messages: 305970
nosy: Richard Neumann
priority: normal
severity: normal
status: open
title: Make iteration over dict_items yield namedtuples
type: enhancement
versions: Python 3.8
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue31992>
_______________________________________
More information about the New-bugs-announce
mailing list