Practice Problems: 2. DataFrames from Dictionaries

Screen Link:

Although the problem asks to create a DataFrame with two dictionaries, I tried first creating it with one dict following the pandas.DataFrame() constructor. It shows this

d = {'col1': [1, 2], 'col2': [3, 4]}

df = pd.DataFrame(data=d)

   col1  col2
0     1     3
1     2     4

If I could create one dictionary, then it could lead me to the answer. So, based on the above, my code for one dictionary was:

life_exp_top10 = pd.DataFrame(data=women)

What actually happened:

ValueError: If using all scalar values, you must pass an index

Also, the solutions provided are a bit different and I could not find the use of {} anywhere.

# Answer 
life_exp_top10 = pd.DataFrame({
    'Women': women,
    'Men': men

# Alternative answer
life_exp_top10 = pd.DataFrame.from_dict({
    'Women': women,
    'Men': men

What did I miss?
Thank you for your feedback :raised_hands:

Hi @boemer00,

Here’s a link from StackOverflow to the error message you are getting. The comments to the answer are in small fonts so they might be easy to miss, but be sure to read those too. You will find clarity on why this error message occurs there.

The {} in the DQ answer are present in the pandas doc:

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)

Note that d is a dictionary. The DQ answer is the equivalent of :

d = { 'Women': women,  'Men': men}
life_exp_top10 = pd.DataFrame(data = d)

Your code life_exp_top10 = pd.DataFrame(data=women) takes the women dictionary, which takes all the keys in the dictionary as column names for the new dataframe and all the float values as the column value, i.e. the scaler values in the error message.

Hope this helps!

1 Like

Hi @veratsien, thanks for the link and the explanation. It makes total sense, now. :blush:

1 Like

Hi @boemer00, please mark @veratsien’s reply as the solution so that others can benefit from it in the future as well!


I do apologise, I did not know I had to tick the solution box.
thanks again

@boemer00 You are good.:blush:

As @the_doctor said, it’s just so others can benefit from the solution in the future. Guidelines like this in the community are for better helping and sharing with each other. You can find most of the guidelines under the Knowledge base tag.

Glad to be of help. Happy coding. :vulcan_salute:

1 Like