0

i have a Dictionary which has key value pairs like below

dict= ('P06', 'P09'): 36340, ('P01', 'P05', 'P06', 'P09'): 10085, ('P01', 'P06'): 36337, ('P01', 'P09'): 49897, ('P02', 'P09'): 11573.....

I want it to be converted into a Dataframe of the below format

Product Id Count Lenght ('P06', 'P09') 36340 2 ('P01', 'P05', 'P06', 'P09') 10085 4 ('P01', 'P06') 36337 2

Any help is greatly appreciated thank you!

Noobpython
  • 23
  • 8
  • 1
    Does this answer your question? [Convert Python dict into a dataframe](https://stackoverflow.com/questions/18837262/convert-python-dict-into-a-dataframe) – Gonçalo Peres Oct 27 '20 at 16:08

1 Answers1

3

Let's try this:

dict= {('P06', 'P09'): 36340, ('P01', 'P05', 'P06', 'P09'): 10085, ('P01', 'P06'): 36337, ('P01', 'P09'): 49897, ('P02', 'P09'): 11573}

df = pd.DataFrame.from_dict(dict, orient='index')

df.rename_axis('Product Id').reset_index()\
  .assign(length = df.index.str.len()).rename(columns={0:'Count'})

Output:

             Product Id  Count  length
0            (P06, P09)  36340       2
1  (P01, P05, P06, P09)  10085       4
2            (P01, P06)  36337       2
3            (P01, P09)  49897       2
4            (P02, P09)  11573       2
Scott Boston
  • 147,308
  • 15
  • 139
  • 187