Reputation: 874
I have a large dictionary and I want to remove certain keys. I defined a set of unwanted keys, let's say it's called kunwanted. The dictionary looks like this:
mydic= {'user':{'key1':'12','key2':'20','key3':30},
'status':{'newk':'12','user':{'key1':'12','key2':'20','key3':30}}}
So, I have key 'user' as a key of mydic and as a key of mydic['status']. Let's say that in kunwanted I have 'key1' and 'key2'. Obviously, I can iterate 2 times through mydic to remove the elements:
for elem in kunwanted:
if elem in mydic['status']['user']:
del mydic['status']['user'][elem]
for elem in kunwanted:
if elem in mydic['user']:
del mydic['user'][elem]
is there a more efficient way to achieve this?
Upvotes: 1
Views: 510
Reputation: 2753
Condensing that into a single for loop should speed up execution slightly.
for elem in kunwanted:
if elem in mydict['status']['user']:
del mydic['status']['user'][elem]
if elem in mydic['user']:
del mydic['user'][elem]
Upvotes: 0
Reputation: 7821
Another recursive approach.
def recursive_remove(u_keys, d):
# Remove keys in current dict
for unwanted_key in u_keys:
try:
del d[unwanted_key]
except (KeyError, TypeError):
continue
# Try to iterate over the items in dict, continue if not iterable
for key, value in d.iteritems():
try:
recursive_remove(u_keys, value)
except AttributeError:
continue
my_dict= {'user':{'key1':'12','key2':'20','key3':30},
'status':{'newk':'12','user':{'key1':'12','key2':'20','key3':30}}}
u_keys = ['key1', 'key2']
recursive_remove(u_keys, my_dict)
Upvotes: 0
Reputation: 7167
Here's a recursive approach:
#!/usr/local/cpython-3.3/bin/python
import pprint
def recursive_remover(unwanted_keys, dictionary):
for key, value in list(dictionary.items()):
if isinstance(value, dict):
recursive_remover(unwanted_keys, value)
if key in unwanted_keys:
del dictionary[key]
def main():
mydict={'user': {'key1':'12','key2':'20','key3':30},
'status':{'newk':'12','user':{'key1':'12','key2':'20','key3':30}}}
unwanted_keys = { 'key1', 'key2' }
recursive_remover(unwanted_keys, mydict)
pprint.pprint(mydict)
main()
Upvotes: 3
Reputation: 2898
I am not sure I am getting it the right way, following might be helpful
for elem in kunwanted:
if elem in mydic['user']:
del mydic['user'][elem]
break #
if elem in mydic['status']['user']:
del mydic['status']['user'][elem]
Upvotes: 0