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

Python嵌套字典中如何将字符串"True"/"False"转为对应布尔值?

Fixing Boolean String to Boolean Value Conversion in Nested Dictionaries

First, let's break down why your original code didn't work:

  • Incorrect loop iteration: When you do for i in a, i is the key string ("b", "c", "d"), not the inner dictionary. Then for j in i loops through each character of that key (e.g., 'b' for the key "b"), so you never actually access the inner dict's keys or values.
  • Comparison instead of assignment: You used j["truth"] == False which only checks equality, not j["truth"] = False which assigns the value. Even if you were targeting the right element, this wouldn't modify the data.

Here's the corrected code that properly converts the "truth" string values to actual booleans:

a = {
    "b": {
        "name": "gari",
        "last_name": "jovan",
        "truth": "True"
    },
    "c": {
        "name": "miki",
        "last_name": "milane",
        "truth": "False"
    },
    "d": {
        "name": "baki",
        "last_name": "mico",
        "truth": "True"
    }
}

# Iterate over each key in the outer dictionary
for outer_key in a:
    inner_dict = a[outer_key]  # Get the inner dictionary for this key
    # Check if "truth" exists to avoid KeyError
    if "truth" in inner_dict:
        truth_str = inner_dict["truth"]
        if truth_str == "False":
            inner_dict["truth"] = False
        elif truth_str == "True":
            inner_dict["truth"] = True
        else:
            raise Exception("Greska")

print(a)

Output:

{
    "b": {"name": "gari", "last_name": "jovan", "truth": True},
    "c": {"name": "miki", "last_name": "milane", "truth": False},
    "d": {"name": "baki", "last_name": "mico", "truth": True}
}

Additional Tips for Your CSV Workflow:

  • CSV files don't natively support boolean types, so csv.DictWriter automatically converts booleans to strings when writing.
  • csv.DictReader reads all values as strings by default, so you need to explicitly convert fields that should be booleans (or numbers, dates, etc.).
  • For a scalable solution, use a helper function to handle conversions when reading from CSV:
    def convert_boolean_fields(row, boolean_fields):
        for field in boolean_fields:
            if field in row:
                val = row[field].lower()
                if val == "true":
                    row[field] = True
                elif val == "false":
                    row[field] = False
                else:
                    raise ValueError(f"Invalid boolean value for {field}: {row[field]}")
        return row
    
    # Usage when reading CSV:
    with open("your_file.csv", "r") as f:
        reader = csv.DictReader(f)
        for row in reader:
            convert_boolean_fields(row, ["truth"])
            # Process the row with correct boolean values
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:30:16