Removing dictionary from a list

Viewed 57

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

4 Answers

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'}]

Also, you can use the built-in filter function with lambda

list(filter(lambda x: not x['codename'].endswith("_templateresource"), b))

If you need to extend code you can do it easily, e.g.

def is_bad(element, bad_suffixes):
    for suffix in bad_suffixes:
        if element.endswith(suffix):
            return True
    return False

bad_suffixes = ['_templateresource','_group']

list(filter(lambda x: not is_bad(x['codename'], bad_suffixes), b))

A comprehension like below can make it out.

d = [ n for n in b if not '_templateresource' in n['codename']]
Related