I've been using dictionary keys as membership markers. Is this a good idea?
For instance, I have a document that has a pile of control codes that I need to manually specify replacements for. I basically write a script that prints out the list of codes. Easy.
Now I've been using a dictionary's k开发者_如何学JAVAey to store the membership. If the code exists, then I set the dictionary value to something, and then I just return the keys of that dictionary. This strikes me as a little wasteful. Is there any better way of doing things?
You should use a set instead.
>>> members = set()
>>> members.add(1)
>>> 1 in members
True
>>> 2 in members
False
If your codes are stored in an iterable then finding the unique codes might be as as simple as:
>>> set(codes)
精彩评论