Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dictionary check if any key other than given keys exist

Lets say I have a dictionary that specifies some properties for a package:

d = {'from': 'Bob', 'to': 'Joe', 'item': 'book', 'weight': '3.5lbs'}

To check the validity of a package dictionary, it needs to have a 'from' and 'to' key, and any number of properties, but there must be at least one property. So a dictionary can have either 'item' or 'weight', both, but can't have neither. The property keys could be anything, not limited to 'item' or 'weight'.

How would I check dictionaries to make sure they're valid, as in having the 'to', 'from', and at least one other key?

The only method I can think of is by obtaining d.keys(), removing the 'from' and 'to' keys, and checking if its empty.

Is there a better way to go about doing this?

like image 990
Vaibhav Aggarwal Avatar asked Dec 14 '22 23:12

Vaibhav Aggarwal


2 Answers

must = {"from", "to"}
print len(d) > len(must) and all(key in d for key in must)
# True

This solution makes sure that your dictionary has more elements than the elements in the must set and also all the elements in must will be there in the dictionary.

The advantage of this solution is that, it is easily extensible. If you want to make sure that one more parameter exists in the dictionary, just include that in the must dictionary, it will work fine. You don't have to alter the logic.

Edit

Apart from that, if you are using Python 2.7, you can do this more succinctly like this

print d.viewkeys() > {"from", "to"}

If you are using Python 3.x, you can simply write that as

print(d.keys() > {"from", "to"})

This hack works because, d.viewkeys and d.keys return set-like objects. So, we can use set comparison operators. > is used to check if the left hand side set is a strict superset of the right hand side set. So, in order to satisfy the condition, the left hand side set-like object should have both from and to, and some other object.

Quoting from the set.issuperset docs,

set > other

Test whether the set is a proper superset of other, that is, set >= other and set != other.

like image 101
thefourtheye Avatar answered May 24 '23 13:05

thefourtheye


if d.keys() has a length of at least 3, and it has a from and to attribute, you're golden.

My knowledge of Python isn't the greatest but I imagine it goes something like if len(d.keys) > 2 and d['from'] and d['to']

like image 31
David Avatar answered May 24 '23 12:05

David