gpt4 book ai didi

python - 根据列表中嵌套字典中的值删除字典元素

转载 作者:太空宇宙 更新时间:2023-11-03 21:22:48 25 4
gpt4 key购买 nike

我正在尝试删除列表中嵌套字典中的元素。因此,我有一个列表,其中的元素之一是字典,而该列表又将字典作为其键值之一。我知道我将在最顶部列表和最底部字典中使用的键,而“中间”字典中的键是可变的。如果底部字典中的值不等于某个值,我想删除“中间”字典中的元素。

我认为我需要三个嵌套的 for 循环才能进入每个字典,但无法弄清楚如何删除“中间”字典中的元素。

到目前为止我目前的尝试:

#remove unneccessary elements
def getCleanResults(the_dict1):
for elem1 in the_dict1:
the_dict2 = elem['dict1_key']
for key, elem2 in the_dict2.keys():
the_dict3 = elem2[key]
for elem3 in the_dict3:
if 'keyWanted' in elem3:
del elem2
return the_dict

我拥有的词典列表模板:

a = {
{'key1':{'key1.1': {'delete': True, 'result': None},
'key1.2': {'delete': False, 'result': None}},'key2': 3},
{'key1':{'key1.1': {'delete': False, 'result': None},
'key1.2': {'delete': True, 'result': None}},'key2': 5}
}

我想删除键keyx.x,其下有一个'delete',即True,这将按照上面的例子,产量:

a = {
{'key1':{'key1.2': {'delete': False, 'result': None}},'key2': 3},
{'key1':{'key1.1': {'delete': False, 'result': None}},'key2': 5}
}

如上例所示,他们删除了键 key1.1key1.2,因此是可变的。

最佳答案

我猜,你的挣扎来自于Python在迭代过程中修改字典的限制。为了制作你想要的东西,你需要复制你的字典——要么复制,迭代,要么删除原始字典中的键;或者迭代原始键并将“过滤”键放入新键中。稍后可以使用

b = {k1: {k2: v2 for k2, v2 in v1.items() if not v2['delete']}
for k1, v1 in a.items()}

编辑:由于某种原因,您提供的代码不一致,上面的解决方案假设结构实际上是

a = {'key1.1': {'key1.1.1': {'delete': True, 'loremipsum': 'perhaps'},
'key1.1.2': {'delete': False, 'loremipsum': 'perhaps'}},
'key1.2': {'key1.2.1': {'delete': False, 'loremipsum': 'perhaps'},
'key1.2.2': {'delete': False, 'loremipsum': 'perhaps'}},
'key2.1': {'key2.1.1': {'delete': False, 'loremipsum': 'perhaps'},
'key2.1.2': {'delete': False, 'loremipsum': 'perhaps'}},
'key2.2': {'key2.2.1': {'delete': False, 'loremipsum': 'perhaps'},
'key2.2.2': {'delete': True, 'loremipsum': 'perhaps'}}
}

b = {'key1.1': {'key1.1.2': {'delete': False, 'loremipsum': 'perhaps'}},
'key1.2': {'key1.2.1': {'delete': False, 'loremipsum': 'perhaps'},
'key1.2.2': {'delete': False, 'loremipsum': 'perhaps'}},
'key2.1': {'key2.1.1': {'delete': False, 'loremipsum': 'perhaps'},
'key2.1.2': {'delete': False, 'loremipsum': 'perhaps'}},
'key2.2': {'key2.2.1': {'delete': False, 'loremipsum': 'perhaps'}}
}

关于python - 根据列表中嵌套字典中的值删除字典元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54109518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com