I am trying to create a set having different values along with True, False, 1, 0.
I am aware that Python treats 1 as True and 0 as False. Imperatively, since the set keeps only the unique values, my set stores either of 1 or True, and of 0 or False.
Is there any workaround to deal with the above requirement?
set1 = {"Python", "Java", 1, 0, 23.45, True, False}
Output1: {"Python", "Java", 1, 0, 23.45}
(not in the same order obviously)
Output2: {"Python", "Java", 1, False, 23.45}
(not in the same order obviously)
I am trying to create a set having different values along with True, False, 1, 0.
I am aware that Python treats 1 as True and 0 as False. Imperatively, since the set keeps only the unique values, my set stores either of 1 or True, and of 0 or False.
Is there any workaround to deal with the above requirement?
set1 = {"Python", "Java", 1, 0, 23.45, True, False}
Output1: {"Python", "Java", 1, 0, 23.45}
(not in the same order obviously)
Output2: {"Python", "Java", 1, False, 23.45}
(not in the same order obviously)
1 Answer
Reset to default 2The problem is, that set’s logic for existence uses both "equality" and "hash", and True==1, as well as hash(1) == hash(True)
So I see only 2 workarounds
You could write your own set with a wrapper (see how contains and add now also checks for "type")
class MySet:
def __init__(self):
self._data = {}
def add(self, item):
key = (type(item), item)
self._data[key] = None
def __contains__(self, item):
key = (type(item), item)
return key in self._data
def __len__(self):
return len(self._data)
def __iter__(self):
for (typ, val) in self._data.keys():
yield val
def __repr__(self):
items = ', '.join(repr(x) for x in self)
return f"MySet({{{items}}})"
s = MySet()
s.add(True)
s.add(1)
s.add(False)
s.add(0)
print(s) # PRINTS MySet({True, 1, False, 0})
OR you could tag them in tuples:
set2 = {
("int", 1),
("bool", True),
("int", 0),
("bool", False),
("str", "Python"),
("str", "Java"),
("float", 23.45),
}
if you want to add something, you could run ( or maybe write add_value method) ?)
value = 1
set2.add(str(type(value)),value)
1 == True
. You can see this related question: stackoverflow/questions/30851580/… If you share the end goal we can try to think of another approach – Gei Stoyanov Commented Mar 17 at 12:45True
andFalse
in your context – Timus Commented Mar 17 at 13:45