字典的循环列表,并使用Python删除/提取具有关键条件的元素



我有一个字典列表,如下所示:

dict_list=[
{
"notes": [
{"Id": "Id1","val": -1},
{"Id": "Id2","val": 0},
{ "Id": "Id3","val": 1}
],
"user_id": "u_id1"
},
{
"notes": [
{"Id": "Id4","val": -1},
{"Id": "Id5","val": 1}
],
"user_id": "u_id2"
},
{
"notes": [
{"Id": "Id4","val": 0}
],
"user_id": "u_id3"
}
]

我想写一个函数,它应该检查和删除输入(dict_list)中的元素,如果" value "=0关于"notes"关键。预期的输出:

dict_list_new=[
{
"notes": [
{"Id": "Id1","val": -1},
{ "Id": "Id3","val": 1}
],
"user_id": "u_id1"
},
{
"notes": [
{"Id": "Id4","val": -1},
{"Id": "Id5","val": 1}
],
"user_id": "u_id2"
}
]

谢谢。

dict_list_new = []
for item in dict_list:
note_list = []
for note_item in item['notes']:
if note_item['val'] != 0:
note_list.append(note_item)
if note_list:
dict_list_new.append({
'notes': note_list,
'user_id': item['user_id'],
})

你可以分两步完成

  1. 删除值为0的音符
  2. 删除带有空注释的对象

def removeZero(obj):
obj['notes'] = list(filter(lambda x: x['val'] != 0, obj['notes']))
return obj

dict_list = map(removeZero, dict_list)  #removes zeroes

def hasNotes(obj):
return len(obj['notes']) != 0
dict_list = list(filter(hasNotes, dict_list))  #removes obj with empty notes
print(dict_list)

这也可以一步完成,但张贴这篇文章是为了便于理解

相关内容

  • 没有找到相关文章

最新更新