Python 从 OrderedDict 中删除键和值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27155819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete a key and value from an OrderedDict
提问by Acoop
I am trying to remove a key and value from an OrderedDictbut when I use:
我正在尝试从 an 中删除一个键和值,OrderedDict但是当我使用时:
dictionary.popitem(key)
it removes the last key and value even when a different key is supplied. Is it possible to remove a key in the middle if the dictionary?
即使提供了不同的键,它也会删除最后一个键和值。如果字典可以删除中间的键吗?
采纳答案by Acoop
Yes, you can use del:
是的,您可以使用del:
del dct[key]
Below is a demonstration:
下面是一个演示:
>>> 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)])
>>>
In fact, you should always use delto remove an item from a dictionary. dict.popand dict.popitemare used to remove an item and return the removed itemso that it can be saved for later. If you do not need to save it however, then using these methods is less efficient.
实际上,您应该始终使用del从字典中删除项目。 dict.pop和dict.popitem用于删除项目并返回删除的项目,以便以后保存。但是,如果您不需要保存它,那么使用这些方法的效率会降低。
回答by Padraic Cunningham
You can use pop, popitem removes the last by default:
可以使用pop,popitem默认删除最后一个:
d = OrderedDict([(1,2),(3,4)])
d.pop(your_key)

