How to Convert Dictionary to Tensor in TensorFlow

Recently, I was working on a machine learning project where I needed to convert Python dictionaries into tensors for processing with TensorFlow. Converting dictionaries to tensors isn’t always simple, especially when dealing with nested data structures.

In this article, I’ll cover several methods to convert Python dictionaries to TensorFlow tensors, with practical examples that you can implement in your projects.

Whether you’re building a recommendation system, processing customer data, or working with any dictionary-based datasets, these techniques will help you seamlessly integrate them into your TensorFlow workflow.

Convert Dictionary to Tensor in TensorFlow

Now, I will explain some important methods to convert a dictionary to a tensor in TensorFlow.

Read Binary Cross-Entropy TensorFlow

Method 1: Use tf.convert_to_tensor() Function

One of the simplest ways to convert a Python dictionary to a tensor is using TensorFlow’s built-in tf.convert_to_tensor() function. This works well for dictionaries with simple structures.

Let’s say we have a dictionary containing product sales data:

import tensorflow as tf

# Simple dictionary with product sales data
sales_dict = {
    'product_a': 150,
    'product_b': 200,
    'product_c': 175,
    'product_d': 225
}

# Convert dictionary values to tensor
sales_tensor = tf.convert_to_tensor(list(sales_dict.values()))

print("Original dictionary:", sales_dict)
print("Tensor from dictionary values:", sales_tensor)

Output:

Original dictionary: {'product_a': 150, 'product_b': 200, 'product_c': 175, 'product_d': 225}
Tensor from dictionary values: tf.Tensor([150 200 175 225], shape=(4,), dtype=int32)

I executed the above example code and added the screenshot.

Convert Dictionary to Tensor in TensorFlow

When you run this code, you’ll get a tensor containing just the values from your dictionary. However, note that we lose the key information in this conversion.

Check out Batch Normalization TensorFlow

Method 2: Convert Dictionary to Tensor with tf.lookup.StaticHashTable

If you need to preserve both keys and values, you can use TensorFlow’s lookup tables:

import tensorflow as tf

# Product inventory dictionary
inventory_dict = {
    'laptop': 45,
    'smartphone': 120,
    'tablet': 75,
    'headphones': 200
}

# Create keys and values tensors
keys = tf.constant(list(inventory_dict.keys()))
values = tf.constant(list(inventory_dict.values()), dtype=tf.int32)

# Create a hash table
table = tf.lookup.StaticHashTable(
    tf.lookup.KeyValueTensorInitializer(keys, values),
    default_value=-1)

# Now you can look up values using the table
print(table.lookup(tf.constant('laptop')))
print(table.lookup(tf.constant('smartphone')))
print(table.lookup(tf.constant('unknown_product')))

Output:

tf.Tensor(45, shape=(), dtype=int32)
tf.Tensor(120, shape=(), dtype=int32)
tf.Tensor(-1, shape=(), dtype=int32)

I executed the above example code and added the screenshot.

Convert Python Dictionary to Tensor in TensorFlow

This approach is especially useful when you need to perform lookups during your model execution.

Read TensorFlow Fully Connected Layer

Method 3: Convert Nested Dictionaries to Tensors

Handling nested Python dictionaries requires a bit more work. Here’s how to convert a nested dictionary structure to tensors:

import tensorflow as tf

# Nested dictionary with customer data
customer_data = {
    'customer_1': {
        'age': 35,
        'purchase_amount': 120.50,
        'is_member': True
    },
    'customer_2': {
        'age': 28,
        'purchase_amount': 85.75,
        'is_member': False
    },
    'customer_3': {
        'age': 42,
        'purchase_amount': 250.00,
        'is_member': True
    }
}

# Extract values as lists
ages = [customer['age'] for customer in customer_data.values()]
purchases = [customer['purchase_amount'] for customer in customer_data.values()]
memberships = [customer['is_member'] for customer in customer_data.values()]

# Convert to tensors
ages_tensor = tf.convert_to_tensor(ages, dtype=tf.int32)
purchases_tensor = tf.convert_to_tensor(purchases, dtype=tf.float32)
memberships_tensor = tf.convert_to_tensor(memberships, dtype=tf.bool)

print("Ages tensor:", ages_tensor)
print("Purchases tensor:", purchases_tensor)
print("Memberships tensor:", memberships_tensor)

Output:

Ages tensor: tf.Tensor([35 28 42], shape=(3,), dtype=int32)
Purchases tensor: tf.Tensor([120.5   85.75 250.  ], shape=(3,), dtype=float32)
Memberships tensor: tf.Tensor([ True False  True], shape=(3,), dtype=bool)

I executed the above example code and added the screenshot.

How to Convert Dictionary to Tensor in TensorFlow

This approach allows you to convert different data types from the nested dictionary into appropriate tensor types.

Check out Tensorflow Convert String to Int

Method 4: Use tf.data.Dataset from Dictionary

For more complex scenarios, especially when building input pipelines for training models, you can convert Python dictionaries to tf.data.Dataset objects:

import tensorflow as tf

# Dictionary with features
housing_data = {
    'square_feet': [1200, 1500, 1800, 2200, 1100],
    'bedrooms': [2, 3, 3, 4, 2],
    'bathrooms': [1, 2, 2, 3, 1],
    'price': [250000, 320000, 375000, 450000, 240000]
}

# Create a dataset from the dictionary
dataset = tf.data.Dataset.from_tensor_slices(housing_data)

# Print the first element
for element in dataset.take(1):
    for feature_name, feature_value in element.items():
        print(f"{feature_name}: {feature_value.numpy()}")

This approach is perfect when you need to feed dictionary data directly into a model training pipeline.

Read TensorFlow Variable

Method 5: Convert Dictionary to Feature Columns

When working with TensorFlow’s high-level APIs like Keras, you might need to convert dictionaries to feature columns:

import tensorflow as tf

# Dictionary with customer features
customer_features = {
    'age': [25, 35, 42, 28, 53],
    'income': [45000, 65000, 85000, 52000, 78000],
    'credit_score': [680, 720, 750, 705, 810]
}

# Convert dictionary to feature columns
feature_columns = []

# Numeric columns
for header in customer_features:
    feature_columns.append(tf.feature_column.numeric_column(header))

# Convert to tensor input layer
feature_layer = tf.keras.layers.DenseFeatures(feature_columns)

# Create tensor inputs from the dictionary
tensor_dict = {k: tf.convert_to_tensor(v) for k, v in customer_features.items()}

# Create feature tensor
features = feature_layer(tensor_dict)

print("Feature tensor shape:", features.shape)
print("Feature tensor:", features.numpy())

This method is particularly useful when building machine learning models in TensorFlow that require structured inputs.

Check out Tensor in TensorFlow

Method 6: Handle Dictionaries with tf.py_function

For complex dictionary processing that can’t be directly represented in TensorFlow’s computational graph, you can use tf.py_function:

import tensorflow as tf
import numpy as np

# Function to process our dictionary
def process_dictionary(dict_data):
    # Convert dictionary values to a numpy array
    values = np.array(list(dict_data.values()), dtype=np.float32)
    # Some processing (e.g., normalization)
    return values / np.max(values)

# Example dictionary
stock_prices = {
    'AAPL': 150.25,
    'MSFT': 260.75,
    'GOOGL': 2150.50,
    'AMZN': 3200.00,
    'FB': 325.50
}

# Wrap the function in tf.py_function
def dict_to_tensor(dict_input):
    return tf.py_function(
        func=process_dictionary,
        inp=[dict_input],
        Tout=tf.float32
    )

# Using the function
normalized_tensor = dict_to_tensor(stock_prices)
print("Normalized tensor:", normalized_tensor)

This approach lets you use Python-native dictionary operations within TensorFlow’s execution.

I hope you found this article helpful for converting dictionaries to tensors in TensorFlow. Remember that the best approach depends on your specific use case and data structure. Whether working with simple dictionaries or complex nested structures, TensorFlow provides multiple ways to transform your data into the tensor format required for deep learning models.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.