How to raise error if user tries to enter duplicate entries in a set in Python?
Question:
I tried to enter 5 similar elements in a set and print it at last. It took all the elements without raising any error but stored only one since all were same. I want to know if it is possible that the moment i input a value which is already present in the set , user is prompted with an error that the value already present in the set. I want to do this with set only , not with list or dict on anything else.
Answers:
You can just check if it exist, then raise an error:
my_set = set()
for i in some_list_of_user_input:
if i in my_set:
raise ValueError(f'{i} is already present in the set')
my_set.add(i)
If you want to raise an exception on duplicate insertion, you could do something like this:
class DuplicateKeyError(Exception): pass
class SingleSet(set):
def add(self, value):
if value in self:
raise DuplicateKeyError('Value {!r} already present'.format(value))
super().add(value)
def update(self, values):
error_values = []
for value in values:
if value in self:
error_values.append(value)
if error_values:
raise DuplicateKeyError('Value(s) {!r} already present'.format(
error_values))
super().update(values)
my_set = SingleSet()
value = 'something'
while value:
value = input('Enter a value: ')
try:
my_set.add(value)
except DuplicateKeyError as e:
print(e)
I tried to enter 5 similar elements in a set and print it at last. It took all the elements without raising any error but stored only one since all were same. I want to know if it is possible that the moment i input a value which is already present in the set , user is prompted with an error that the value already present in the set. I want to do this with set only , not with list or dict on anything else.
You can just check if it exist, then raise an error:
my_set = set()
for i in some_list_of_user_input:
if i in my_set:
raise ValueError(f'{i} is already present in the set')
my_set.add(i)
If you want to raise an exception on duplicate insertion, you could do something like this:
class DuplicateKeyError(Exception): pass
class SingleSet(set):
def add(self, value):
if value in self:
raise DuplicateKeyError('Value {!r} already present'.format(value))
super().add(value)
def update(self, values):
error_values = []
for value in values:
if value in self:
error_values.append(value)
if error_values:
raise DuplicateKeyError('Value(s) {!r} already present'.format(
error_values))
super().update(values)
my_set = SingleSet()
value = 'something'
while value:
value = input('Enter a value: ')
try:
my_set.add(value)
except DuplicateKeyError as e:
print(e)