0
0
Pandasdata~20 mins

Creating DataFrame from list of dictionaries in Pandas - Practice Exercises

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
DataFrame Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this DataFrame creation?
Given the list of dictionaries, what will be the output DataFrame?
Pandas
import pandas as pd

data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
df = pd.DataFrame(data)
print(df)
A
   name  age
0  Alice  25.0
1    Bob  30.0
B
   name  age
0  Alice   25
1    Bob   30
C
   name  age
0  Alice   25
1    Bob  NaN
D
   name  age
0  Alice  NaN
1    Bob   30
Attempts:
2 left
💡 Hint
Each dictionary becomes a row; keys become columns.
data_output
intermediate
1:30remaining
How many rows and columns does this DataFrame have?
What is the shape (rows, columns) of the DataFrame created from this list?
Pandas
import pandas as pd

data = [{'x': 1, 'y': 2}, {'x': 3, 'z': 4}, {'y': 5, 'z': 6}]
df = pd.DataFrame(data)
print(df.shape)
A(3, 3)
B(3, 2)
C(2, 3)
D(2, 2)
Attempts:
2 left
💡 Hint
Count unique keys across all dictionaries for columns; count dictionaries for rows.
🔧 Debug
advanced
2:00remaining
What error does this code raise?
Identify the error raised by this code snippet:
Pandas
import pandas as pd

data = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]
df = pd.DataFrame(data, columns=['a', 'c'])
print(df)
AKeyError
BTypeError
CNo error, prints DataFrame with NaN in column 'c'
DValueError
Attempts:
2 left
💡 Hint
Check how pandas handles missing columns when specifying columns parameter.
🚀 Application
advanced
2:30remaining
Which option creates a DataFrame with only keys 'name' and 'score'?
Given this list of dictionaries, which code creates a DataFrame with only 'name' and 'score' columns?
Pandas
data = [{'name': 'Anna', 'score': 90, 'age': 20}, {'name': 'Ben', 'score': 85, 'age': 22}]
AAll of the above
Bpd.DataFrame(data).drop('age', axis=1)
Cpd.DataFrame([{k: d[k] for k in ['name', 'score']} for d in data])
Dpd.DataFrame(data, columns=['name', 'score'])
Attempts:
2 left
💡 Hint
Consider how each method selects or removes columns.
🧠 Conceptual
expert
3:00remaining
What happens when dictionaries have nested dictionaries as values?
If you create a DataFrame from a list of dictionaries where some values are nested dictionaries, what is the type of those nested values in the DataFrame?
Pandas
import pandas as pd

data = [{'id': 1, 'info': {'height': 170, 'weight': 65}}, {'id': 2, 'info': {'height': 180, 'weight': 75}}]
df = pd.DataFrame(data)
print(type(df.loc[0, 'info']))
A<class 'float'>
B<class 'str'>
C<class 'pandas.Series'>
D<class 'dict'>
Attempts:
2 left
💡 Hint
Think about how pandas stores complex objects inside cells.