0

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.

1
  • Don't use built-in function names as variables especially when you're using dict to represent a list! Commented Nov 16, 2022 at 12:49

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your guidance, I just edited my question. I wanted to split the name with - and then I need to follow the rule, In that case what I should do?
With \w you will also accept a value like "123456".
@Matthias - yes. that's why i said to check.
@moses - in that case update the regex to match what you need. docs.python.org/3/library/re.html
1

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

1 Comment

Thanks for your guidance, I just edited my question. I wanted to split the name with - and then I need to follow the rule, In that case what I should do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.