Skip to content
Advertisement

Tag: set

Convert set to string and vice versa

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:

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 issues with the set literal syntax: It’s

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.JSONEncoder class that has a

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?

Advertisement