I gave a Python dictionary that looks something like:
myDict = {'A':['a','b','c','d','e'],
'B':['f','g','h']}
I would like to convert this to a Pandas dataframe that has the following structure:
key val
0 B f
1 B g
2 B h
3 A a
4 A b
5 A c
6 A d
7 A e
I can't use the standard method to enter a dictionary into a Pandas dataframe but I have come up with a method that works but seems a but clunky. Basically, I create 2 lists containing the keys and the values, convert to a another dict and import that dict into a Pandas dataframe. I'm sure I could combine some of the lines using list or dictionary comprehensions but the final command would be unreadable. I've kept each line separate for the moment to make reading the code easier.
myDict = {'A':['a','b','c','d','e'],
'B':['f','g','h']}
# Column of keys
keys = [[k]*len(v) for k,v in myDict.items()]
# Flatten list
keys = [item for sublist in keys for item in sublist]
# Column of values
values = [v for k,v in myDict.items()]
# Flatten list
values = [item for sublist in values for item in sublist]
key = 'key'
value = 'val'
df = pd.DataFrame({key:keys,value:values})
print(df)
Perhaps I've been staring at this too long but my question is whether there is a simpler, built-in command to achieve the same goal.