Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricted set operations on python dictionary key views

Tags:

python

set

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?

like image 807
DurgaDatta Avatar asked Aug 03 '16 23:08

DurgaDatta


People also ask

How to use set operation on the keys of dictionary?

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.

What are the restrictions of a dictionary key?

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.

What is the use of dictionary in Python?

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.

What is set in Python?

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 (^).


1 Answers

Why, for example, are not side-effect free operation like issuperset or issubset 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}))
like image 111
user2357112 supports Monica Avatar answered Oct 19 '22 00:10

user2357112 supports Monica