Pandas Dataframe from Dict key and list of values to have same key for multiple rows

dictionary, pandas, python

Solution

Here is one simple way:

>>> pandas.DataFrame({"A": 'City', "B": d['City']})
      A      B
0  City  Item1
1  City  Item2
2  City  Item3
3  City  Item4
4  City  Item5

Problem

I have created a dictionary by: ``` test_df = {} for row in df.iterrows(): y = [] for x in row[1]: y.append(x) test_df[y[0]] = y[1:] ``` So my dict looks like this: ``` {'City': ['Item1', 'Item2', 'Item3', 'Item4', 'Item5']} ``` I can't seem to get a dataframe that looks like this: ``` A B 'City' 'Item1' 'City' 'Item2' 'City' 'Item3' 'City' 'Item4' 'City' 'Item5' ``` I want to have the dictionary key be in each row for every item in the list its associated with. I've tried making two series and concat them but it didn't work. I must be over thinking this. Thanks in advance for any insight. So BrenBarn got me onto the right path so I did the following: ``` x = [item[0] for item in test_df.items()] df1 = pd.DataFrame({'A': x[0], 'B': test_df[x[0]]}) for row in x[1:]: df2 = pd.DataFrame({'A': row, 'B': test_df[row]}) df1 = pd.concat([df1, df2]) ``` It worked beautifully. Thanks guys.

Original source