I have following list:
b = [{'codename': 'add_group', 'id': 5, 'content_type': 2, 'name': 'Can add group'},
{'codename': 'change_group', 'id': 6, 'content_type': 2, 'name': 'Can change group'},
{'codename': 'delete_group', 'id': 7, 'content_type': 2, 'name': 'Can delete group'},
{'codename': 'view_group', 'id': 8, 'content_type': 2, 'name': 'Can view group'},
{'codename': 'add_templateresource', 'id': 21, 'content_type': 6, 'name': 'Can add template resource'},
{'codename': 'change_templateresource', 'id': 22, 'content_type': 6, 'name': 'Can change template resource'},
{'codename': 'delete_templateresource', 'id': 23, 'content_type': 6, 'name': 'Can delete template resource'},
{'codename': 'view_templateresource', 'id': 24, 'content_type': 6, 'name': 'Can view template resource'},
{'codename': 'add_usermodel', 'id': 13, 'content_type': 4, 'name': 'Can add user'},
{'codename': 'change_usermodel', 'id': 14, 'content_type': 4, 'name': 'Can change user'},
{'codename': 'delete_usermodel', 'id': 15, 'content_type': 4, 'name': 'Can delete user'},
{'codename': 'view_usermodel', 'id': 16, 'content_type': 4, 'name': 'Can view user'}]
Now I want to delete the dictionary that whose value contains _templateresource substring in codename key
I think the easiest approach would be to filter those entries out using a list comprehension:
result = [i for i in b if not i['codename'].endswith('_templateresource')]
You can iterate over a copy of the list and remove the matching dictionaries
for d in b[:]:
if '_templateresource' in d['codename']:
b.remove(d)
print(b)
# [{'codename': 'add_group', 'id': 5, 'content_type': 2, 'name': 'Can add group'},
# {'codename': 'change_group', 'id': 6, 'content_type': 2, 'name': 'Can change group'},
# {'codename': 'delete_group', 'id': 7, 'content_type': 2, 'name': 'Can delete group'},
# {'codename': 'view_group', 'id': 8, 'content_type': 2, 'name': 'Can view group'},
# {'codename': 'add_usermodel', 'id': 13, 'content_type': 4, 'name': 'Can add user'},
# {'codename': 'change_usermodel', 'id': 14, 'content_type': 4, 'name': 'Can change user'},
# {'codename': 'delete_usermodel', 'id': 15, 'content_type': 4, 'name': 'Can delete user'},
# {'codename': 'view_usermodel', 'id': 16, 'content_type': 4, 'name': 'Can view user'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With