Building Dynamic JSON Keys Using Variables in Python

In this tutorial, we will explore different methods to dynamically build and modify JSON keys using variables in Python.

Whether you’re a beginner or an experienced Python developer, these insights will enhance your coding toolkit.



Using Dictionary Comprehension

You can create a dictionary where keys are dynamically generated using dictionary comprehension by replacing variables using string interpolation:

user_data_usage = [(101, 2.5), (102, 5.7), (103, 3.1)]
data_usage_dict = {f"user_{user_id}": usage for user_id, usage in user_data_usage}


{'user_101': 2.5, 'user_102': 5.7, 'user_103': 3.1}

In this example, the dictionary data_usage_dict is created with keys that dynamically combine the string “user_” with each user ID.

The values correspond to the data usage of each user.


Using the dict() Constructor

This method is useful where the keys and values are generated or fetched at runtime.

Let’s consider a scenario where you want to create a dictionary where each user ID becomes a dynamic key, and the corresponding data plan is the value.

Here’s how you can do this using the dict() constructor:

user_data_plans = [(201, 'Plan A'), (202, 'Plan B'), (203, 'Plan C')]
data_plan_dict = dict((f"user_{user_id}", plan) for user_id, plan in user_data_plans)


{'user_201': 'Plan A', 'user_202': 'Plan B', 'user_203': 'Plan C'}

In this code, dict() is used along with a generator expression. This expression creates tuples where the first element is a dynamic key (f"user_{user_id}") and the second element is the data plan.

The dict() constructor then converts these tuples into key-value pairs in the resulting dictionary.


Modify Keys

Updating keys in a dictionary can be done by changing the variables that define these keys.

Let’s say you created a dictionary with user IDs as keys for storing data usage, but now you need to modify these keys to include the month of usage.

Here’s how you can update the key variables to change the JSON keys:

data_usage = {'user_101': 2.5, 'user_102': 5.7, 'user_103': 3.1}
month = 'Dec'
updated_data_usage = {f"{key}_{month}": value for key, value in data_usage.items()}


{'user_101_Dec': 2.5, 'user_102_Dec': 5.7, 'user_103_Dec': 3.1}

In this example, a new variable month is introduced. The dictionary comprehension is used to iterate over the existing dictionary data_usage.

For each key-value pair, a new key is constructed by appending the month variable to the original key.


Limitations and Workarounds

Let’s explore some of these limitations and the corresponding workarounds.

JSON Key Ordering

In JSON, the order of keys is not guaranteed. When converting a Python dictionary to JSON, the order of keys might not be preserved, which can be problematic in certain cases.

Workaround: Use collections.OrderedDict in Python. This ensures that the order of keys is maintained as they are added to the dictionary.

from collections import OrderedDict
ordered_data = OrderedDict([('user_301', 'Plan X'), ('user_302', 'Plan Y'), ('user_303', 'Plan Z')])


OrderedDict([('user_301', 'Plan X'), ('user_302', 'Plan Y'), ('user_303', 'Plan Z')])

Here, OrderedDict maintains the order of insertion, which can be important for some JSON applications.

Restrictions on Key Names

JSON keys must be strings. While Python dictionaries can have keys of various data types, JSON only supports string keys.

Workaround: Ensure all dictionary keys are strings before converting to JSON. If necessary, convert non-string keys to strings.

data_usage = {101: 2.5, 102: 5.7, 103: 3.1}
str_key_data_usage = {str(key): value for key, value in data_usage.items()}


{'101': 2.5, '102': 5.7, '103': 3.1}
Leave a Reply

Your email address will not be published. Required fields are marked *