我僅在滿足條件時才嘗試從串列中洗掉字典。嵌套字典中有 with key decision = "Remove",我希望只保留 with 的元素key decision = "keep"。
例如,
mylist = [
{
"id": 1,
"Note": [
{
"xx": 259,
"yy": 1,
"decision": "Remove"
},
{
"xx": 260,
"yy": 2,
"decision": "keep"
}
]
},
{
"id": 1,
"Note": [
{
"xx": 303,
"yy": 2,
"channels": "keep"
}
]
}
]
輸出:
[
{
"id": 1,
"Note": [
{
"xx": 260,
"yy": 2,
"decision": "keep"
}
]
},
{
"id": 1,
"Note": [
{
"xx": 303,
"yy": 2,
"channels": "keep"
}
]
}
]
我的解決方案:這似乎不對。
for d in mylist:
for k,v in enumerate(d['Note']):
if v["decision"] == "Remove":
del d[k]
請問有什么幫助嗎?
uj5u.com熱心網友回復:
與@sushanth 的回答非常相似。不同之處在于,它與字典中的其他鍵值對無關,并且只洗掉決策為“洗掉”的字典:
for d in mylist:
d['Note'] = [inner for inner in d['Note'] if inner.get('decision')!='Remove']
輸出:
[{'id': 1, 'Note': [{'xx': 260, 'yy': 2, 'decision': 'keep'}]},
{'id': 1, 'Note': [{'xx': 303, 'yy': 2, 'channels': 'keep'}]}]
uj5u.com熱心網友回復:
嘗試使用list comprehension
print(
[
{
"id": i['id'],
"Note": [j for j in i['Note'] if j.get('decision', '') == 'keep']
}
for i in mylist
]
)
[{'id': 1, 'Note': [{'xx': 260, 'yy': 2, 'decision': 'keep'}]}, {'id': 1, 'Note': []}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/449006.html
標籤:Python python-3.x 列表 字典
上一篇:Python:決議日期時間字串時引發ValueError
下一篇:格式化條件陳述句的最佳方法
