2

Take the dictionary:

dict = {'a':'ham', 'b': 'ham', 'c': 'chicken', 'd': 'beef', 'e': 'chicken'}

how do I take this dictionary and turn it into a dataframe where the values are the columns? i.e. I want a dataframe showing:

   ham   chicken  beef
0   a       c       d
1   b       e       

Can't seem to get it of this form at all!

Thanks

This is a different question, the other is simply asking how to get values of a dictionary into a dataframe, I am asking how to get that particular form I outlined

user33484
  • 740
  • 2
  • 9
  • 36

2 Answers2

2

A little bit of conversion "magic":

import pandas as pd

d = {'a':'ham', 'b': 'ham', 'c': 'chicken', 'd': 'beef', 'e': 'chicken'}

new_dict = dict()
for key in d:
    col = d[key]
    try:
        new_dict[col].append(key)
    except:
        new_dict[col] = [key]

df = pd.DataFrame.from_dict(new_dict, orient='index').transpose()
print(df)

#   chicken ham  beef
# 0       c   a     d
# 1       e   b  None

First, walk through your original dictionary and create a list in a new dict called new_dict. From this one call from_dict() with orient='index'.

Jan
  • 42,290
  • 8
  • 54
  • 79
2

I see Jan just posted a great answer, but I wanted to show that you can also use defaultdict and list comprehensions to do this.

import pandas as pd
from collections import defaultdict

dict1 = {'a':'ham', 'b': 'ham', 'c': 'chicken', 'd': 'beef', 'e': 'chicken'}

# Set the default as an empty list to store multiple strings with an order
reversed_dict = defaultdict(list)

# Reverse the key-value pairs
for k, v in dict1.items():
    reversed_dict[v].append(k)

# Convert each list to a Series and make the dataframe
pd.DataFrame(dict([(k, pd.Series(v)) for k, v in reversed_dict.items()]))

#   beef chicken ham
# 0    d       c   a
# 1  NaN       e   b
Nick Becker
  • 4,059
  • 13
  • 19