If i
is not in hashTable
, you'll get a KeyError
. It's not like in some other languages like JavaScript where you get undefined
out, which is falsy (Boolean(undefined) === false
).
Instead, you can check if i
is in hashTable
, since it doesn't really matter if it's True
, as long as it's present.
if i in hashTable:
However, your code doesn't actually work. The output is 'i'
. You need to read the whole string to find non-duplicate characters. I recommend using a Counter
:
def nonDuplicate(string):
from collections import Counter
c = Counter(string)
for x, count in c.items():
if count == 1:
return x
print(nonDuplicate('minimum')) # -> n
Note: If you're using Python 3.6 or lower, this might return 'u'
instead of 'n'
since dicts weren't necessarily order-preserving.