Python: How to dynamically get values from dictionary with dynamic key and plot it to DataFrame?

Viewed 533

I want to make a DataFrame from each of these dictionaries:

ig_dict = {'Instagram': ([{'photos': 2}], [{'videos': 1}])}
tw_dict = {'Twitter': ([{'photos': 3}], [{'videos': 7}], [{'status': 5}])}
fb_dict = {'Facebook': ([{'photos': 1}], [{'videos': 1}], [{'status': 8}])}

This is my desired output for the Dataframe:

Dataframe 1: (from ig_dict)
       Instagram
photos         2      
videos         1
Dataframe 2: (from tw_dict)
       Twitter
photos       3      
videos       7      
status       5
Dataframe 3: (from fb_dict)
       Facebook
photos        1      
videos        1      
status        8

Currently, I am using .from_dict() method:

dataframe_to_plot_ig = pd.DataFrame.from_dict({k: v for k, v in ig_dict.items()}, orient='index')
dataframe_to_plot_tw = pd.DataFrame.from_dict({k: v for k, v in tw_dict.items()}, orient='index')
dataframe_to_plot_fb = pd.DataFrame.from_dict({k: v for k, v in fb_dict.items()}, orient='index')

but instead I get the dictionary with both key and value on the DataFrame column. This is the current output:

         Instagram
0  [{'photos': 2}]
1  [{'videos': 1}]
           Twitter
0  [{'photos': 3}]
1  [{'videos': 7}]
2  [{'status': 5}]
          Facebook
0  [{'photos': 1}]
1  [{'videos': 1}]
2  [{'status': 8}]

What kind of list comprehension that I can use for this case?

1 Answers

You can use this.

import pandas as pd

def generate_dataframe(in_hash,key=None):
    val = []
    col = []
    for tup in in_hash:
        for lst in in_hash[tup]:
            for inner_key in lst:
                for final_key in inner_key:
                    val += [inner_key[final_key]]
                    col += [final_key]

    df = pd.DataFrame(data=[val],index=[key],columns=col)

    return df


ig_dict = {'Instagram': ([{'photos': 2}], [{'videos': 1}])}

print(generate_dataframe(ig_dict,key='Instagram'))


O/P ---->

           photos  videos
Instagram       2       1

You can use the general function to create a different DataFrame based on the key supplied. The catch being the structure should be consistent

Related