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,iis the key string ("b", "c", "d"), not the inner dictionary. Thenfor j in iloops 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"] == Falsewhich only checks equality, notj["truth"] = Falsewhich 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.DictWriterautomatically converts booleans to strings when writing. csv.DictReaderreads 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
相关产品推荐
相关产品推荐

