Popping key causes dict derived from object to revert to object

Jon Ribbens jon+usenet at unequivocal.eu
Mon Mar 25 11:19:17 EDT 2024


On 2024-03-25, Loris Bennett <loris.bennett at fu-berlin.de> wrote:
> "Michael F. Stemper" <michael.stemper at gmail.com> writes:
>
>> On 25/03/2024 01.56, Loris Bennett wrote:
>>> Grant Edwards <grant.b.edwards at gmail.com> writes:
>>> 
>>>> On 2024-03-22, Loris Bennett via Python-list <python-list at python.org> wrote:
>>>>
>>>>> Yes, I was mistakenly thinking that the popping the element would
>>>>> leave me with the dict minus the popped key-value pair.
>>>>
>>>> It does.
>>> Indeed, but I was thinking in the context of
>>>    dict_list = [d.pop('a') for d in dict_list]
>>> and incorrectly expecting to get a list of 'd' without key 'a',
>>> instead
>>> of a list of the 'd['a]'.
>> I apologize if this has already been mentioned in this thread, but are
>> you aware of "d.keys()" and "d.values"?
>>
>>  >>> d = {}
>>  >>> d['do'] = 'a deer, a female deer'
>>  >>> d['re'] = 'a drop of golden sunshine'
>>  >>> d['mi'] = 'a name I call myself'
>>  >>> d['fa'] = 'a long, long way to run'
>>  >>> d.keys()
>>  ['fa', 'mi', 'do', 're']
>>  >>> d.values()
>>  ['a long, long way to run', 'a name I call myself', 'a deer, a female deer', 'a drop of golden sunshine']
>>  >>>
>
> Yes, I am, thank you.  However, I didn't want either the keys or the
> values.  Instead I wanted to remove a key within a list comprehension.

Do you mean something like:

  [my_dict[key] for key in my_dict if key != 'a']

?


More information about the Python-list mailing list