You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从嵌套字典提取多层键值对并转换为Pandas DataFrame?

Solution to Flatten Nested Dictionary into Target 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 12:32:29