根据python中嵌套词典中的键删除项目 [英] Deleting Items based on Keys in nested Dictionaries in python
问题描述
我的字典像这样:
{
'key1':
{
'a': 'key1',
'b': 'val1',
'c': 'val2'
},
'key2':
{
'a': 'key2',
'b': 'val3',
'c': 'val4'
},
'key3':
{
'a': 'key3',
'b': 'val5',
'c': 'val6'
}
}
我试图根据键"a"删除嵌套字典中的元素,以得到如下输出:
I trying to delete the elements in the nested dict based on the key "a" to get an output like this:
{
'key1':
{
'b': 'val1',
'c': 'val2'
},
'key2':
{
'b': 'val3',
'c': 'val4'
},
'key3':
{
'b': 'val5',
'c': 'val6'
}
}
我为此编写了以下代码段:
I wrote the following snippet for it:
for k in dict_to_be_deleted:
del k["a"]
我不断收到关键错误:找不到k.我也尝试了以下方法:
I keep getting Key Error: k not found. I tried the following method as well:
for i in dict_to_be_deleted:
for k,v in i.items():
if "a" in k:
del i[k]
我知道
Attribute Error: str object has no attribute items
但是因为 dict_to_be_deleted
是嵌套的字典,所以它不是应该是字典吗?我对此很困惑.我非常感谢在这方面的任何指示.
But isn't it suppose to be a dictionary since dict_to_be_deleted
is a nested dictionary? I am pretty confused with this. I greatly appreciate any pointers in this regard.
推荐答案
在字典上进行迭代时, dict_to_be_deleted
仅在键上进行迭代.因此,在第二次尝试中,您的 Attribute Error
是因为 i
是键,而不是字典,是字符串.实际执行此操作的方法将是使用 .values()
代替,它会遍历值.
When you're iterating over a dictionary, dict_to_be_deleted
you are only iterating over the keys. So in your second attempt, your Attribute Error
is because i
is the key, a string not the dictionary. How you could actually perform it would be to use .values()
which iterates over the values instead.
for v in dict_to_be_deleted.values():
del v["a"]
但是,就我个人而言,我建议不要遵循删除元素的方法,而是遵循Ajax的方法并构建一个没有缺失元素的新字典.像我们在这里所做的那样的怪异突变是获取错误的简便方法.
However, personally, instead of deleting the elements, I'd suggest following Ajax's method and building a new dictionary without the missing elements. Weird mutations like what we're doing here is an easy way to get bugs.
这篇关于根据python中嵌套词典中的键删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!