Reading dataframe from dictionary of lists

Question:

I have a dictionary like below:

d={0:[('cat_a', 15),('cat_b', 12)], 
1: [('cat_a',10),('cat_b',7)],
2:[('cat_a', 12),('cat_b', 8)]}

I get a dataframe by using below:

data = [l for l in d.values()]
df=pd.DataFrame(data,columns=['cat_a','cat_b'])

In each column i get tuples, out of which i only need the numerical value.

Asked By: Tranquil Oshan

||

Answers:

Try:

df = pd.DataFrame(map(dict, d.values()))
print(df)

Prints:

   cat_a  cat_b
0     15     12
1     10      7
2     12      8
Answered By: Andrej Kesely

You can use:

df = pd.DataFrame.from_dict({k: {k2:v2 for k2,v2 in l} for k,l in d.items()}, orient='index')

# or for a functional approach like that of @Andrej
df = pd.DataFrame.from_dict(dict(zip(d, map(dict, d.values()))), orient='index')

output:

   cat_a  cat_b
0     15     12
1      7     10
2     12      8

used input:

d = {0: [('cat_a', 15),('cat_b', 12)], 
     1: [('cat_b',10),('cat_a',7)],
     2: [('cat_a', 12),('cat_b', 8)]}
Answered By: mozway