What about keys that contain invalid characters for attribute names?
items = {'1': 1, 'two-3': 4,}
x = object()
x.__dict__.update(items) # dangerous
x = AttrDict(**items)
x.1 # error
x.two-3 # error
On Saturday, November 30, 2019, Eric V. Smith <eric@trueblade.com> wrote:
> On 11/30/2019 8:51 PM, Andrew Barnert via Python-ideas wrote:
>>
>> On Nov 30, 2019, at 16:36, Oscar Benjamin <oscar.j.benjamin@gmail.com> wrote:
>>>
>>> On Sat, 30 Nov 2019 at 22:24, Steven D'Aprano <steve@pearwood.info> wrote:
>>>>>
>>>>> On Sat, Nov 30, 2019 at 06:16:49PM -0300, Soni L. wrote:
>>>>>
>>>>> It'd be quite nice if dict.items() returned a namedtuple so all these
>>>>> x[0], x[1], el[0], el[1], etc would instead be x.key, x.value, el.key,
>>>>> el.value, etc. It would be more readable and more maintainable.
>>>>
>>>> If you are doing
>>>>
>>>> for item in somedict.items():
>>>> process(item[0])
>>>> process(item[1])
>>>>
>>>> you could do this instead:
>>>>
>>>> for key, value in somedict.items():
>>>> process(key)
>>>> process(value)
>>>
>>> You can also make your own function to get the items as namedtuples.
>>> That can work now with any class that defines items the current way.
>>>
>>> from collections import namedtuple
>>>
>>> Item = namedtuple('Item', ['key', 'value'])
>>>
>>> def nameditems(d):
>>> return (Item(*t) for t in d.items())
>>>
>>> d = {'a': 1, 'b': 2}
>>>
>>> for item in nameditems(d):
>>> print(item.key, item.value)
>>>
>>> Comparing that with Steve's example above though I don't see the
>>> advantage of namedtuples here.
>>
>> Presumably the main advantage is for cases where you can’t destructure the tuple in-place:
>>
>> sorted(d.items(), key=lambda it: it.value)
>>
>> There’s no nice way to write that today. Maybe this makes it clear?
>>
>> sorted(d.items(), key=(ValueGetter := operator.itemgetter(1)))
>>
>> But normally you don’t bother; you just live with using [1] and assuming your reader will know that [1] on a mapping item is the value. Which isn’t terrible, because it almost always is obvious you’ve got a mapping item, and almost every reader does know what [1] means there. But it’s not as nice as using .value would be.
>
> How I miss python 2's parameter unpacking:
>
>>>> sorted({1:300, 2:4}.items(), key=lambda (key, value): value)
> [(2, 4), (1, 300)]
>
> Eric
> _______________________________________________
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-leave@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/HRCAVIV4KYIPMQ5C7SGX2C5OW6IPU5JG/
> Code of Conduct: http://python.org/psf/codeofconduct/
>