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

如何在将特定格式字符串转换为字典时,为字符值保留字符串类型、为数值转换为对应数值类型

Solution to Convert String to Typed Dictionary

Got it, let's get your string-to-dictionary conversion sorted so values are properly typed—strings stay as strings, and numbers (integers, floats, negatives) become their correct numeric types. Here's how you can adjust your existing function:

Modified Function Code

def str_to_conf_dict(input_str):
    def convert_value(value):
        # Attempt to convert to integer first, then float; fall back to string if both fail
        try:
            return int(value)
        except ValueError:
            try:
                return float(value)
            except ValueError:
                return value
    
    # Split the input string, process each key-value pair, and build the dictionary
    return dict(
        (key, convert_value(val)) 
        for key, val in (pair.split('=') for pair in input_str.split(';'))
    )

Test It Out

Let's verify with your example plus some edge cases like floats and negatives:

# Test input with mixed value types
test_input = "a=b;b=2;c=3.14;d=-5"
result = str_to_conf_dict(test_input)

print(result)
# Output: {'a': 'b', 'b': 2, 'c': 3.14, 'd': -5}

# Check the types to confirm correctness
print(type(result['a']))  # <class 'str'> (stays as string)
print(type(result['b']))  # <class 'int'> (converted to integer)
print(type(result['c']))  # <class 'float'> (converted to float)
print(type(result['d']))  # <class 'int'> (negative integer works too)

How It Works

  • The inner convert_value helper function handles the type conversion logic:
    1. First tries to convert the value to an integer using int()—this works for positive/negative whole numbers.
    2. If that fails (throws a ValueError), it tries converting to a float with float()—this catches decimal numbers like 3.14 or -2.5.
    3. If both conversion attempts fail, the value is returned as-is (keeping it as a string for non-numeric values).
  • The main function splits the input string by semicolons to get key-value pairs, splits each pair by equals signs, then applies the conversion to each value before building the dictionary.

This approach ensures your dictionary matches the exact type requirements your downstream function needs, no modifications needed for that function.

内容的提问来源于stack exchange,提问作者Janani Ethirraj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 18:07:33