简体   繁体   中英

Problem with validation of schema in python

For my script, I need to check if some object is a list of dictionnaries or a list of list of dictionnaries in order to perform corresponding actions, or else raise an error.

To be more specific, the following should be accepted (with two different conditions):

mylist = [{'a': 1, 'b': 2}, {'c': 3},{'d': 4}]
mylist1 = [[{'a':1}, {'ccc':4}], [{'e': 3}]]

but, for instance, the following should raise an error:

c = [[]]
d = [[{'a':1}], {'b':2}]

I have implemented a naive solution as follows:

if set([type(x) for x in mylist]) == set([dict]):
    print('first case')
elif set([type(x) for x in mylist]) == set([list]) and set([type(x) for y in mylist for x in y ])== set([dict]):
    print('second case')
else:
    raise Exception('wrong structure')

I tried using a schema validation but I do not seem to get how to do that. Any help to make this more readable / elegant would be appreciated!!

Thanking you in advance,

M

The problem is, that type(dict) evaluates as type as dict is already type designation.

So, you would need to change if set([type(x) for x in mylist]) == set([type(dict)]) to if set([type(x) for x in mylist]) == set([dict])

Also, it's not very good idea to throw general Exception , you can, eg use TypeError for this type of Exception

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM