How to remove a key from a 2 dimensional dictionary in Python?
I am trying to use pop
to remove a key from a 2 dimensional dictionary. I keep thinking that forward_hash[first_key].pop(second开发者_如何学编程_key)
should work but it's not.
It appears to work for me:
>>> forward_hash = {"first_key": {"second_key": "data"}}
>>> forward_hash["first_key"].pop("second_key")
'data'
>>> forward_hash
{'first_key': {}}
If you're looking to remove second_key
from all of your dicts, you should do:
forward_hash = dict( a=dict(...), b=dict(...), ...)
second_key = "blah"
for d in forward_hash.itervalues():
d.pop(second_key)
Not sure if you intended to use pop(). Usually to delete a key from a dictionary I would use the del
operator:
>>> forward_hash = {"first_key": {"second_key": "data"}}
>>> del forward_hash["first_key"]["second_key"]
>>> forward_hash
{'first_key': {}}
See this article for more details and other info on using dicts.
Seems to work just fine for me:
>>> d = {'a': {'b': 'c'}}
>>>
>>> d
{'a': {'b': 'c'}}
>>> d['a']
{'b': 'c'}
>>> d['a'].pop('b')
'c'
>>> d['a']
{}
>>>
精彩评论