I got very good help for question check if dictionary key has empty value . But I was wondering if there is a difference between and
and &
in python? I assume that they should be similar?
dict1 ={"city":"","name":"yass","region":"","zipcode":"",
"phone":"","address":"","tehsil":"", "planet":"mars"}
whitelist = {"name", "phone", "zipcode", "region", "city",
"munic", "address", "subarea"}
result = {k: dict1[k] for k in dict1.viewkeys() & whitelist if dict1[k]}
&
is the bit-wise and operator,and
is the boolean logic operator. They're quite different, don't confuse them! For example:Yes
and
is a logical and whereas&
is a bitwise and. See example -The first result is due to short circuiting. Python tests 1 and finds it true and returns the 2. But, the second part does 01 (Binary 1) & 10 (Binary 2) hence evaluating to 00 (1 & 0, 0 &1) , which is 0.
and
is logical and&
is bitwise andlogical
and
returns the second value if both values evaluate to true.For sets
&
is intersection.If you do:
This be because
bool(a) == True
andbool(b) == True
soand
returns the second set.&
returns the intersection of the sets.(
set
doc)and
is a logical operator which is used to compare two values, IE:&
is a bitwise operator that is used to perform a bitwise AND operation:Update
With respect to set operations, the
&
operator is equivalent to theintersection()
operation, and creates a new set with elements common to s and t:and
is still just a logical comparison function, and will treat aset
argument as a non-false value. It will also return the last value if neither of the arguments isFalse
:For what its worth, note also that according to the python docs for Dictionary view objects, the object returned by
dict1.viewkeys()
is a view object that is "set-like":