我有一个大字典,我想删除某些键。我定义了一组不需要的键,假设它叫做kunwanted。字典看起来像这样:
mydic= {'user':{'key1':'12','key2':'20','key3':30},
'status':{'newk':'12','user':{'key1':'12','key2':'20','key3':30}}}
所以,我将关键'用户'作为mydic的关键,并作为mydic ['status']的关键。让我们说在kunwanted我有'key1'和'key2'。显然,我可以通过mydic迭代2次以删除元素:
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]
有更有效的方法来实现这个目标吗?
答案 0 :(得分:2)
这是一种递归方法:
#!/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()
答案 1 :(得分:0)
我不确定我是否采用了正确的方式,以下可能会有所帮助
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]
答案 2 :(得分:0)
另一种递归方法。
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)
答案 3 :(得分:0)
将其压缩为单个for循环应该会略微加快执行速度。
for elem in kunwanted:
if elem in mydict['status']['user']:
del mydic['status']['user'][elem]
if elem in mydic['user']:
del mydic['user'][elem]