Python @ DjangoSpin

PyPro #25 Unique Characters in a string using a dictionary

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Unique Characters in a string using a dictionary in Python: Write a Python program which asks the user for a string, and outputs number of unique characters in it. For example: 'Ethan' has 5 unique characters, 'Hello' has 4. Use a dictionary to achieve the functionality, not a set. Hint: Once a key is registered in a dictionary, you can assign values to it any number of times.

Unique Characters in a string using a dictionary in Python

enteredString = input("Please enter a string: ")

# Initialize the uniqueCharacters dictionary
uniqueCharacters = dict()

# Iterater over each character, and register it in the dictionary with any value. Any repeated occurence of a letter will reassign the given value to it, without creating a duplicate key.
for character in enteredString:
    uniqueCharacters[character] = True

print("The entered string contains", len(uniqueCharacters), "unique character(s).")
Try it here.

See also:


Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon