Retrieving an element from a set

I have a set of strings. Given a string equal to one in that set, I'd like to retrieve the literal object that is in the set.

In other words, I need to know what I can put into the ???? below, some operation on the_set and another_abc, so that the final check is true:

>>> abc_in_set = "ABC"
>>> the_set = {abc_in_set}

>>> import ast
>>> another_abc = ast.literal_eval("'ABC'")   # make sure we're getting a different object...
>>> another_abc is abc_in_set
False

>>> set_contents =  ????
>>> set_contents is abc_in_set
True

I can do this using a dict instead of set by mapping every element to itself:

>>> the_set = {abc_in_set: abc_in_set}

>>> set_contents = the_set[another_abc]
>>> set_contents is abc_in_set
True

and this is okay, but is there a better way so I can use the data structure that actually corresponds to the meaning of what it's holding?

Posted Jan 11, 2024, 7:13 AM UTC

13

Comments aren't archived yet

This post had 3 comments on Reddit. Comments for this period haven't been loaded into the archive yet.