I have a dictionary where for each key, a single value is stored. Say
import pandas as pd
dd = {'Alice': 40,
'Bob': 50,
'Charlie': 35}
Now, I want to cast this dictionary to a pd.Dataframe with two columns. The first column contains the keys of the dictionary, the second column the values and give the columns a name (Say "Name" and "Age"). I expect to have a function call like:
pd.DataFrame(dd, columns=['Name', 'Age'])
which gives not desired output, since it only has 0 rows.
Currently I have two "solutions":
# Rename the index and reset it:
pd.DataFrame.from_dict(dd, orient='index', columns=['Age']).rename_axis('Name').reset_index()
pd.DataFrame(list(dd.items()), columns=['Name', 'Age'])
# Both result in the desired output:
Name Age
0 Alice 40
1 Bob 50
2 Charlie 35
However, both appear a bit hacky and thus inefficient and error-prone to me. Is there a more pythonic way to achieve this?
pd.DataFrame(dd.items(), columns=['Name', 'Age'])to get the needed result in your case \$\endgroup\$