Set to string. Obvious: String to set? Maybe like this? Extremely ugly. Is there better way to serialize/deserialize sets? Answer Use repr and eval: Note that eval is not safe if the source of string is unknown, prefer ast.literal_eval for safer conversion: help on repr:
Tag: set
Use curly braces to initialize a Set in Python
I’m learning python, and I have a novice question about initializing sets. Through testing, I’ve discovered that a set can be initialized like so: Are there any disadvantages of doing it this way, as opposed to the standard way of: or is it just a question of style? Answer There are two obvious is…
How to JSON serialize sets?
I have a Python set that contains objects with __hash__ and __eq__ methods in order to make certain no duplicates are included in the collection. I need to json encode this result set, but passing even an empty set to the json.dumps method raises a TypeError. I know I can create an extension to the json.JSONE…
Get difference between two lists with Unique Entries
I have two lists in Python: Assuming the elements in each list are unique, I want to create a third list with items from the first list which are not in the second list: Are there any fast ways without cycles and checking? Answer To get elements which are in temp1 but not in temp2 (assuming uniqueness of the …
How to retrieve an element from a set without removing it?
Suppose the following: How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it – something I can only be sure of after an asynchronous call to another host. Quick and dirty: But do you know of a better way?