开发者

Why can't I call del [:] on a dict?

开发者 https://www.devze.com 2023-02-04 03:19 出处:网络
What\'s going on here? >>> a = {1: \"a\", 2: \"b\"} >>> del a[1] >>> a {2: \'b\'}

What's going on here?

>>> a = {1: "a", 2: "b"}
>>> del a[1]
>>> a
{2: 'b'}
>>> a = {1: "a", 2: "b"}
>>> del a[:]
Traceback (most r开发者_如何转开发ecent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type
>>> a.clear()
>>> a
{}

Why must I call dict.clear?


a[:] is a special case of a slicing operation, which is defined only for sequences. It is a short form of a[0:len(a)]. A dict is not a sequence.


a[:] is a quick way to make a shallow copy of a list (and tuple). See towards the bottom of the docs for clarification on different types of copying.

Thus, it would reason to say that del a[:] on a dictionary doesn't really make much sense.

If you want to delete the entire dictionary, you can simply do del a

>>> a = {1: "a", 2: "b"}
>>> del a
>>> a

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    a
NameError: name 'a' is not defined
>>>


The reason is rather simple: It isn't defined. There's no reason why it couldn't work, if someone put the effort into catching the empty slice and delegating to the appropriate method.

On the other hand, this would violate a symmetry principle with assigning and getting the same slice, so probably would not gain acceptance.


If this functionality is crucial to your system, you could subclass the dict builtin to add this function.

import sys
class newdict(dict):

    def __delslice__(self,i,j):
        if i==0 and j==sys.maxint:
            self.clear()
        else:
            dict.__delslice__(self,i,j)


When you're doing del a[1] you're not deleting the first element in dictionary, you're deleting the element with key 1. Dictionary does not have any ordering and thus slicing algorigthm (in this case at least). That's why with the dict a = {1 : 'one', 5 : 'five'} you can do del a[1] and cannot do del a[2] or del a[0]

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号