Zipping dictionary to pandas

I am trying to zip my dictionary into a panda’s data frame, and do it by the keys that are in the dictionary and not manually:

import pandas as pd

dict = {'A': ['a1', 'a2', 'a3'], 'B': ['b1', 'b2', 'b3']}
columns = list(dict.keys())   # ['A', 'B']
manual_results = list(zip(dict['A'], dict['B'])) #  [('a1', 'b1'), ('a2', 'b2'), ('a3', 'b3')]
df = pd.DataFrame(manual_results, columns=columns)

I wish to create the results without the need to explicitly write the name of each key (dict[‘A’], dict[‘B’] etc). Any Ideas?

>Solution :

There is no need to zip it. Pandas can create a dataframe directly from a dict:

import pandas as pd
d = {'A': ['a1', 'a2', 'a3'], 'B': ['b1', 'b2', 'b3']}
df = pd.DataFrame.from_dict(d)
print(df)
    A   B
0  a1  b1
1  a2  b2
2  a3  b3

reference: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.from_dict.html


Note: You can also orient it the other way (so the dict keys become the row index instead of colums) …

import pandas as pd
d = {'A': ['a1', 'a2', 'a3'], 'B': ['b1', 'b2', 'b3']}
df = pd.DataFrame.from_dict(d,orient='index')
print(df)
    0   1   2
A  a1  a2  a3
B  b1  b2  b3

Leave a Reply