Aco*_*oop 25 python dictionary ordereddictionary
我试图删除一个键和值,OrderedDict但我使用时:
dictionary.popitem(key)
Run Code Online (Sandbox Code Playgroud)
即使提供了不同的密钥,它也会删除最后一个密钥和值.如果字典,是否可以删除中间的键?
iCo*_*dez 39
是的,你可以使用del:
del dct[key]
Run Code Online (Sandbox Code Playgroud)
以下是演示:
>>> from collections import OrderedDict
>>> dct = OrderedDict()
>>> dct['a'] = 1
>>> dct['b'] = 2
>>> dct['c'] = 3
>>> dct
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
>>> del dct['b']
>>> dct
OrderedDict([('a', 1), ('c', 3)])
>>>
Run Code Online (Sandbox Code Playgroud)
实际上,您应该始终使用del从字典中删除项目. dict.pop并dict.popitem用于删除项目并返回已删除的项目,以便以后保存.但是,如果您不需要保存它,那么使用这些方法效率会降低.
你可以使用pop,popitem默认删除最后一个:
d = OrderedDict([(1,2),(3,4)])
d.pop(your_key)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28887 次 |
| 最近记录: |