Search code examples
pythonpytorch

python dict pop could not return pytorch tensor


My code is as follows:

import torch

mydict = {"state0": torch.tensor(12345.6), "state1":torch.tensor(23456.7)}
print(f"mydict: {mydict}")

val = mydict.pop("state0")
print(f"val={val}")

The output is:

mydict: {'state0': tensor(12345.5996), 'state1': tensor(23456.6992)}
val=12345.599609375

Here why the pop() does not return tensor(12345.5996)? I need it to be a tensor instead of a scalar.


Solution

  • As mentioned in the previous answer, pop is not the issue.

    The issue is when you format the string using the f-string. When you pass the tensor to the f-string, Python calls the __format__() method of the tensor object which converts the tensor to scalar.

    To print the tensor object itself, directly pass it to the print function without using the f-sting formatter.

    Or you can even use the repr() function:

    import torch
    
    mydict = {"state0": torch.tensor(12345.6), "state1":torch.tensor(23456.7)}
    
    val = mydict.pop("state0")
    print("val=", repr(val))