How Python3 deletes dictionary elements in the most elegant way

Python generally uses the following four methods to delete dictionary elements:

  • clear(): Delete all elements in the dictionary.

  • pop(): Remove dictionary given key keyvalue corresponding to the return value is deleted.

  • popitem(): Randomly return and delete a pair of keys and values ​​in the dictionary.

  • del: A single element can be deleted and the dictionary can be cleared. Clearing only requires one operation.

But this way is not elegant, here is a very elegant way:

Python 2.7

>>> data = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> map(data.pop, ['a', 'c'])
[1, 3]
>>> data
{'b': 2, 'd': 4}

But I Python3did not delete the.

>>> data = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> map(data.pop, ['a', 'c'])
<map object at 0x7faabf344580>
>>> data
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

why?

This is because Python2the mapfunction returns listan object, and Python3the mapfunction returns an iterator. Iterator is inert sequence, you need to call to perform, so our dictelements are not poplost, deleted in order to achieve that we need to do this once.

>>> data = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> [value for value in map(data.pop, ['a', 'c'])]
[1, 3]
>>> data
{'b': 2, 'd': 4}

that's it!

but! Do you think it's over like this? ! !

. . . The feature film begins. . .

There is a problem with the method mentioned above, that is, what happens if there are no elements in the dictionary? Then you can only report an error.

If we execute the code just once:

>>> [value for value in map(data.pop, ['a', 'c'])]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
KeyError: 'a'

Is there a way to avoid errors?

What are you thinking about?

Of course there is!

>>> [value for value in map(lambda index: data.pop(index) if data.get(index) else None, ['a', 'c'])]
[None, None]
>>> data
{'b': 2, 'd': 4} 

Use anonymous functions and ternary expressions (conditional short-circuit)!

In this way, you can execute it unlimited times without any problem!

Guess you like

Origin blog.csdn.net/yilovexing/article/details/108774389