python - 从 Python 中的 dict 内的列表中删除元素
问题描述
{
'tbl':'test',
'col':[
{
'id':1,
'name':"a"
},
{
'id':2,
'name':"b"
},
{
'id':3,
'name':"c"
}
]
}
我有一本像上面这样的字典,我想id=2
从里面的列表中删除元素。我浪费了半天时间想知道为什么modify2
不使用del
操作。试过了pop
,它似乎工作,但我不完全明白为什么del
不工作。
有没有办法删除 usingdel
或 pop 是解决这个用例的理想方法?
import copy
test_dict = {'tbl': 'test', 'col':[{'id':1, 'name': "a"}, {'id':2, 'name': "b"}, {'id':3, 'name': "c"}]}
def modify1(dict):
new_dict = copy.deepcopy(dict)
# new_dict = dict.copy()
for i in range(len(dict['col'])):
if dict['col'][i]['id'] == 2:
new_dict['col'].pop(i)
return new_dict
def modify2(dict):
new_dict = copy.deepcopy(dict)
# new_dict = dict.copy()
for i in new_dict['col']:
if i['id']==2:
del i
return new_dict
print("Output 1 : " + str(modify1(test_dict)))
print("Output 2 : " + str(modify2(test_dict)))
输出:
Output 1 : {'tbl': 'test', 'col': [{'id': 1, 'name': 'a'}, {'id': 3, 'name': 'c'}]}
Output 2 : {'tbl': 'test', 'col': [{'id': 1, 'name': 'a'}, {'id': 2, 'name': 'b'}, {'id': 3, 'name': 'c'}]}
我试图寻找类似问题的答案,但没有找到能消除我困惑的答案。
解决方案
在 Python 3 中,您可以这样做:
test_dict = {**test_dict, 'col': [x for x in test_dict['col'] if x['id'] != 2]}
推荐阅读
- json - jq to_entries 字符串和数字不能加
- python - 我有批量 csv 文件,我想在字典中读取它,然后将字典再次写入新的 csv 文件,
- android - 如何禁用 Kotlin Android 扩展插件生成合成视图属性
- firebase - 分布式计数器真的需要事务吗?
- php - 不允许在 php preg_match regexp 中使用免费电话号码
- php - 拉拉维尔。存储:FTP、S3 或?对于非常大的文件
- service - azure-active-directory 生成 AAD 服务主体密钥
- java - 使用 XY 坐标获取视图中坐标的高度 - Android
- java - 从 JSONArray 中提取字符串
- kubernetes - 在 Prometheus 中对两个不同的指标进行分组后如何划分?