1

I have a list like this:

mylist = [("elem","str"), ("123","int"),("1.0","float")]

For each tuple, the first element is the data, and the second element is the original type of that data, so I want to convert it to it.

As a result, I want:

mylist = ["elem",123,1.0]

How can I dynamically convert an object given the target data type?

I want to avoid this:

for el in mylist:
    if el[1]=="str":
        result=el[0]
    elif el[1]=="int":
        result=int(el[0])
    elif el[1]=="float":
        result=float(el[0])
kuonb
  • 198
  • 10
  • `from pydoc import locate; [locate(y)(x) for x, y in mylist]` – user2390182 Jan 09 '18 at 06:19
  • I wouldn't recommend the `pydoc` solution, as its not really intended for this purpose. If you only need to support a few types, you could use a mapping from name to type, e.g. `{"int": int, "float": float}`. There are lots of types though that your current serialization can't handle, since not all types can load themselves from a string (you can't build a dict, for instance). You may want to use `pickle` if you need to support arbitrary types. Even if your data types are simple, a more standard serialization like JSON or YAML might be better than something you make up yourself. – Blckknght Jan 09 '18 at 07:54

0 Answers0