State the output of the following code fragment.
import pandas as pd
listDict = [{'a':10, 'b':20}, {'a':5, 'b':10, 'c':20}]
dF = pd.DataFrame(listDict)
print(dF)
State the output of the following code fragment.
import pandas as pd
listDict = [{'a':10, 'b':20}, {'a':5, 'b':10, 'c':20}]
dF = pd.DataFrame(listDict)
print(dF)
Solution
A list of dictionaries creates a DataFrame in which each dictionary becomes one row, and the keys become the column labels. The row index is 0, 1.
The first dictionary has no key 'c', so pandas fills that cell with NaN. Because of the NaN, column c becomes float, so its values print as NaN and 20.0, while a and b stay as integers.
| a | b | c | |
|---|---|---|---|
| 0 | 10 | 20 | NaN |
| 1 | 5 | 10 | 20.0 |
Options 2 and 4: these show the dictionaries as columns (keys as rows), which is what happens when a dictionary of lists or Series is passed, not a list of dictionaries.
Option 1: the missing 'c' in the first dictionary is filled with 20.0 instead of NaN; pandas never copies values into missing keys.
Related questions:
2025: 21 May Shift 1
2026: 18 May Shift 2
2025: 15 May Shift 2