I have a nested dictionary stored in the variable nested_dict_variable
. The dictionary is retrieved by using SPSS valueLabels Property (Python)
I am trying to convert this nested dictionary into a pandas DataFrame. Here is my code:
nested_dict_variable
nested_dict_manual = {
0: {1.0: '1 - low', 2.0: '2', 3.0: '3', 4.0: '4', 5.0: '5 - high', 99.0: "99 - don't know"},
1: {1.0: '1 - low', 2.0: '2', 3.0: '3', 4.0: '4', 5.0: '5 - high', 99.0: "99 - don't know"},
2: {1.0: '1 - low', 2.0: '2', 3.0: '3', 4.0: '4', 5.0: '5 - high', 99.0: "99 - don't know"},
3: {0.0: '0 - no', 1.0: '1 - yes'},
4: {0.0: '0 - no', 1.0: '1 - yes'},
5: {0.0: '0 - no', 1.0: '1 - yes'},
6: {1.0: '1 - low', 2.0: '2', 3.0: '3', 4.0: '4', 5.0: '5 - high', 99.0: "99 - don't know"},
7: {1.0: '1 - low', 2.0: '2', 3.0: '3', 4.0: '4', 5.0: '5 - high', 99.0: "99 - don't know"},
8: {1.0: '1 - low', 2.0: '2', 3.0: '3', 4.0: '4', 5.0: '5 - high', 99.0: "99 - don't know"},
9: {1.0: 'Germany'},
10: {1.0: '1 - A', 2.0: '2 - B', 3.0: '3 - C'}
}
nested_dict = nested_dict_manual
# convert nested dictionary to Pandas DataFrame
data_list = []
for outer_key, inner_dict in nested_dict.items():
for inner_key, value in inner_dict.items():
data_list.append({'Outer Key': outer_key, 'Inner Key': inner_key, 'Value': value})
df = pd.DataFrame(data_list)
This works when I copy & paste the content of nested_dict_variable
into nested_dict_manual
and declare nested_dict = nested_dict_manual
. The resulting DataFrame df
looks like this:
However, if I declare nested_dict = nested_dict_variable
I get an error message when running the code AttributeError: 'ValueLabel' object has no attribute 'items'
Why does the code work with the copy & paste dictionary but fails otherwise?
1