In Tensorflow 2.0 (compatibility with earlier versions not tested) use tf.lookup:
dictionary = {1:3, 2:4}
origin_tensor = tf.Variable([1,2,1], dtype=tf.int64)
note: dict is reserved in python so it is replaced with dictionary and dtype=tf.int32 is replaced with dtype=tf.int64 for compatibility with tf.lookup.KeyValueTensorInitializer
This is the original tensor:
origin_tensor
>> <tf.Variable 'Variable:0' shape=(3,) dtype=int64, numpy=array([1, 2, 1])>
This is the Tensorflow lookup table made from a key-value tensor initialized from a python dictionary:
table = tf.lookup.StaticVocabularyTable(
tf.lookup.KeyValueTensorInitializer(
list(dictionary.keys()),
list(dictionary.values()),
key_dtype=tf.int64,
value_dtype=tf.int64,
),
num_oov_buckets=1,
)
This is the actual lookup that returns the result_tensor with desired elements based on the lookup table:
result_tensor = table.lookup(origin_tensor)
Here is the result:
result_tensor
>> <tf.Tensor: id=400475, shape=(3,), dtype=int64, numpy=array([3, 4, 3])>
Cheers!