Lets see the code snippet below:
d = {1:1}
keys = d.keys()
print(keys & {1,2,3})# {1}
d[2] = 2
print(keys & {1,2,3}) # {1,2} # keys() is a view/reference
print({1,2}.issubset({1,2,3})) # True
print(keys.issubset({1,2,3})) # 'dict_keys' object has no attribute 'issubset'
It is mentioned in the official documents on dictionary view objects:
Keys views are set-like since their entries are unique and hashable. .. Then these set operations are available (“other” refers either to another view or a set): [&,|, ^, ^]
If the keys are set-like, why are the set operation on them restricted to those four infix operations. Why, for example, side-effect free operation like issuperset
or issubset
not permitted?
We can use set operation on the keys of a dictionary such as, union (|), intersection (&), difference (-), symmetric difference (^). Now in a dictionary, when we have the same keys we can use set to identify the unique keys. Set can be very useful when we are working with two dictionaries. Let’s understand this with an example.
But there are a few restrictions I want to briefly talk about. Keys in a dictionary can only be used once. If it is used more than once, as you saw earlier, it’ll simply replace the value. 00:19 A key must be immutable—that is, unable to be changed. These are things like integers, floats, strings, Booleans, functions.
Dictionary is a unique collection in Python. It contains key-value pairs. Dictionary can also contain tuple, sets and lists. We can access values in the dictionaries by their keys. Dictionary has varied uses, as it can hold any type of data in it.
Set: Set can be defined as a collection of elements where all elements are unique. To know more about sets, please click here. We can use set operation on the keys of a dictionary such as, union (|), intersection (&), difference (-), symmetric difference (^).
Why, for example, are not side-effect free operation like
issuperset
orissubset
operation not permitted?
They are; you just have to use the >=
and <=
operators:
print(keys <= {1, 2, 3})
They also support isdisjoint
in method form, since there's no operator for it:
print(keys.isdisjoint({1, 2, 3}))
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