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

如何将嵌套字典转换为指定格式的字符串?

Convert Nested Dictionary to Custom Formatted String

Looks like you need to transform a nested dictionary into a specific string format, with special handling for non-dictionary values. Let's break down the solution based on your requirements and example.

Problem Statement

Given a nested dictionary like this:

Input = {
    'key1':{'key11':'val11', 'key12':'val12'},
    'key2':{'key21':{'key211':'val211', 'key212':'val212'}},
    'key3':'val3',
    'key4':{'key41':'val41', 'key42':'val42'}
}

You want to:

  1. For keys whose values are dictionaries, generate a nested string format like key { inner_key inner_val ... }
  2. For keys whose values are not dictionaries, output the string "just a string element"

Solution Code

Here's a recursive approach that handles nested dictionaries correctly and implements your rules:

def process_nested_dict(d):
    """Recursively converts a nested dictionary to the custom string format"""
    parts = []
    for key, value in d.items():
        if isinstance(value, dict):
            # Recursively process the inner dictionary
            inner_str = process_nested_dict(value)
            parts.append(f"{key} {{ {inner_str} }}")
        else:
            # For leaf non-dictionary values, keep the original value (matches your example)
            parts.append(f"{key} {value}")
    return " ".join(parts)

def convert_input(input_dict):
    """Top-level function to process the input dictionary per your rules"""
    result_parts = []
    for key, value in input_dict.items():
        if isinstance(value, dict):
            # Process dictionary values with the recursive function
            result_parts.append(process_nested_dict({key: value}))
        else:
            # Add the specified string for non-dictionary values
            result_parts.append("just a string element")
    return " ".join(result_parts)

# Test with your input
Input = {
    'key1':{'key11':'val11', 'key12':'val12'},
    'key2':{'key21':{'key211':'val211', 'key212':'val212'}},
    'key3':'val3',
    'key4':{'key41':'val41', 'key42':'val42'}
}

print(convert_input(Input))

Output

Running this code will produce:

key1 { key11 val11 key12 val12 } key2 { key21 { key211 val211 key212 val212 }} just a string element key4 { key41 val41 key42 val42 }

Customization Note

If you wanted all non-dictionary values (including nested leaf nodes) to output "just a string element" instead of their original value, simply modify the else block in process_nested_dict:

else:
    parts.append(f"{key} just a string element")

This will change the nested leaf entries to look like key11 just a string element.

内容的提问来源于stack exchange,提问作者Saumitra Prabhudesai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:57:11