如何从嵌套字典提取多层键值对并转换为Pandas DataFrame?
Got it, let's fix this nested dictionary issue so you can get exactly the DataFrame structure you're looking for. The core problem here is that your original data has nested dictionaries (plrName and statValues) that aren't being unpacked with your current code. Here's how to solve it step by step:
Step 1: Flatten the Nested Dictionary
First, we need a helper function to unpack nested dictionaries and merge their key-value pairs into the top-level. This replaces parent keys like plrName with their inner keys (e.g., last, first) directly:
def flatten_nested_dict(input_dict): flattened = {} for key, value in input_dict.items(): # Check if the value is a non-empty dictionary if isinstance(value, dict) and value: # Merge inner key-value pairs into the top-level flattened.update(value) else: # Keep top-level key-value pairs as-is flattened[key] = value return flattened
Step 2: Process Your Data and Create the DataFrame
Now use this function to flatten your data, then convert it to the DataFrame format you want:
import pandas as pd # Your original data data = { 'plrNum': '29221', 'plrName': {'last': 'Simpson', 'first': 'Webb', 'middle': '', 'nickname': ''}, 'statValues': {'rndEvents': '8', 'statValue1': '1,660', 'statValue2': '2', 'statValue3': '6', 'statValue4': '', 'statValue5': ''}, 'curRank': '1', 'curRankTied': '', 'prevRank': '1', 'prevRankTied': '' } # Flatten the nested dict flattened_data = flatten_nested_dict(data) # Convert to DataFrame with index as keys df = pd.DataFrame.from_dict(flattened_data, orient='Index') # Print the result print(df)
Result
Running this code will give you exactly the structure you requested:
0 plrNum 29221 last Simpson first Webb middle nickname rndEvents 8 statValue1 1,660 statValue2 2 statValue3 6 statValue4 statValue5 curRank 1 curRankTied prevRank 1 prevRankTied
Bonus: Handle Deeply Nested Dictionaries
If you ever have dictionaries nested more than two levels deep, you can use a recursive version of the flatten function to unpack all levels automatically:
def flatten_deep_dict(input_dict): flattened = {} for key, value in input_dict.items(): if isinstance(value, dict) and value: # Recursively flatten inner dictionaries flattened.update(flatten_deep_dict(value)) else: flattened[key] = value return flattened
内容的提问来源于stack exchange,提问作者sousvidesteak

