megacolorboy

Back

Published on August 23rd, 2020

Python

Extract unique characters from a string

I thought of getting back into competitive programming again and started practicing my python coding-chops on Codewars.Here's a neat trick on how to extract unique characters from a string:Using allows you to preserve the order in which the keys are inserted as a normal doesn't track the order.Hope you found this useful!

1 minute read

I thought of getting back into competitive programming again and started practicing my python coding-chops on Codewars.

Here's a neat trick on how to extract unique characters from a string:


from collections import OrderedDict

word = "HelloWorld"
uniq = ''.join(OrderedDict.fromkeys(word).keys())

print(uniq) # prints HeloWrd

Using OrderedDict allows you to preserve the order in which the keys are inserted as a normal dict doesn't track the order.

Hope you found this useful!