Home > Enterprise >  Delete dictionary from JSON based on condition in Value - Python
Delete dictionary from JSON based on condition in Value - Python

Time:11-16

I have JSON as follows

dict =[
{'name':'Test01-Serial01'
},
{'name':'Tests04-Serial04'
}
]

First I wanted to separate the name with - and then with the index 0 that is Test01 I wanted to delete the dictionary which don't follow the rule in name Rule: 4 Digit Word 2 Digit Number

Here Tests04 doesn't follow 4 Digit Word 2 Digit Number rule and it contains 5 digit word.

CodePudding user response:

You can also use regular expressions to parse the values:

import re

mylist = [
    {'name': 'Test01' },
    {'name': 'Tests04' }
]

regex = re.compile(r'^\w{4}\d{2}$')
mylist = [{k:v} for _ in mylist for k,v in _.items() if regex.match(v)]

# Or, maybe this is more clear?
# mylist = [item for item in mylist if regex.match(list(item.values())[0])]

print(mylist)

This returns:

[{'name': 'Test01'}]

This says to look for four "word" characters then two digits between the start and end of the value of each object. Anything that doesn't match this pattern is filtered out. Check out the definition of \w to make sure that you and the authors of re agree on what word chars are.

And, as @cobra pointed out, using dict as a variable name (particularly for a list) is not best practice.

CodePudding user response:

Write a function that validates the value according to your rules. Reconstruct the original list with a list comprehension.

from string import ascii_letters, digits


def isvalid(s):
    return len(s) == 6 and all(c in ascii_letters for c in s[:4]) and all(c in digits for c in s[4:])


_list = [
    {'name': 'Test01-Serial01'},
    {'name': 'Tests04-Serial04'}
]
_list = [e for e in _list if isvalid(e['name'].split('-')[0])]

print(_list)

Output:

[{'name': 'Test01-Serial01'}]
  • Related