Predictive Hacks

How to Convert a key-value array dictionary to key-value JSON

Depending on the API, sometimes we need to change the structure of the dictionary before we convert it to JSON. For example, assume that we have the following dictionary.

my_dict = {'variant_id' : [1,2,3],
           'impressions' : [100, 120, 90]}


{'variant_id': [1, 2, 3], 'impressions': [100, 120, 90]}

Let’s say that we want to generate a JSON file of the following form:

[{'variant_id': 1, 'impressions': 100},
 {'variant_id': 2, 'impressions': 120},
 {'variant_id': 3, 'impressions': 90}]

We can generate this file as follows:

import json
my_json = [{"variant_id":int(i), "impressions":j} for i,j in zip(my_dict['variant_id'],my_dict['impressions'])]     
my_json = json.dumps(my_json)  


'[{"variant_id": 1, "impressions": 100}, {"variant_id": 2, "impressions": 120}, {"variant_id": 3, "impressions": 90}]'

Finally, if we want to convert the JSON to Pandas data frame:

import pandas as pd


Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore


Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.


Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s