如何用字典推导式遍历嵌套字典并解决字符串拼接TypeError报错
问题根因
你触发TypeError: can only concatenate str (not "dict") to str报错的核心原因是字典中fruta2对应的value为嵌套字典类型,无法直接和字符串执行拼接操作。
解决方案
方案1:适配固定两层嵌套场景
如果你的字典最多只有两层嵌套,直接在遍历逻辑中增加类型判断,嵌套字典单独遍历即可,代码如下:
dictionary = {'fruta1': 'Pera', 'fruta2': {'fruta3': 'aguacates', 'fruta4':'limones'} } texto_list = [] for key, value in dictionary.items(): if isinstance(value, dict): texto_list.append(f"{key}:") for sub_key, sub_value in value.items(): texto_list.append(f" {sub_key}: {sub_value}") else: texto_list.append(f"{key}: {value}") texto = '\n'.join(texto_list) print(texto)
输出效果:
fruta1: Pera fruta2: fruta3: aguacates fruta4: limones
方案2:适配任意深度嵌套场景
如果字典存在多层嵌套的可能,可以用递归函数统一处理所有层级的键值对,代码如下:
def parse_dict(input_dict: dict, indent_level: int = 0) -> list: result_list = [] indent_prefix = " " * indent_level for key, value in input_dict.items(): if isinstance(value, dict): result_list.append(f"{indent_prefix}{key}:") result_list.extend(parse_dict(value, indent_level + 1)) else: result_list.append(f"{indent_prefix}{key}: {value}") return result_list dictionary = {'fruta1': 'Pera', 'fruta2': {'fruta3': 'aguacates', 'fruta4':'limones'} } texto = '\n'.join(parse_dict(dictionary)) print(texto)
内容的提问来源于stack exchange,提问作者Lord_Amenegg
相关产品推荐
相关产品推荐

