Python Forum

Full Version: looking fo an expression that yields a dictionary without an item
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i am wanting to make an expression (method call?) that given a dictionary (or set or frozenset), and a hashable value, makes a shallow copy of the dictionary (or set or frozenset) without the item having a key of the hashable value, if one exists in the original unchanged dictionary (or set or frozenset). i only need to do this with a dictionary but i can see potential equivalency for a set or frozenset. at first i wrote d.copy().some_method() but i could not find a method that returned a reference to the dictionary, much less delete an item. i need to do separate steps for this (maybe in a function). the cases i have are difficult to either do separate steps or def a function.

this is another example where if we could add methods to existing builtin classes like dict, it would be an easier solution.

could this be done as a dictionary view? my use case may be able to use that.
do you mean something like this:

>>> example_dict = {
   'field1': 'value1',
   'complex_field': {
       'part1': 'stuff',
       'part2': 'more stuff'
   }
}
>>> cmplx = example_dict['complex_field']
>>> cmplx['part2']
'more stuff'
>>>
cmplx is essentially a (in C terminology) pointer to the complex_field cell of the dictionary, which
can be used as if it were a separate dictionary.
this seems to work:
Output:
>>> d={'foo':1,'bar':2} >>> v='bar' >>> dict([x for x in d.items() if x[0] != v]) {'foo': 1}

no, nothing meant about 'complex_field'.
If dictionary is large then you can save memory by using generator:

>>> dict(x for x in d.items() if x[0] != v)
I tried to understand problem you are solving:
  • given a dictionary (or set or frozenset)
  • a hashable value
  • a shallow copy of the dictionary (or set or frozenset)
  • without the item having a key of the hashable value

Dictionary keys must be hashable, so mentioning hashability seems irrelevant.

Is it complicated way to say that you want to have 'new dictionary where specific keys of original dictionary are omitted' Smile ?
For me, the fastest way is
c = d.copy()
c.pop('bar')
(tested with the timeit module)
if i didn't mention hashability, i'm sure someone would inform me that it won't work for all possible values.

i was trying to get this into an expression.