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?
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
.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With