如何在Python中将包含多个字典的字符串转换为单个字典
多拼接字典字符串转单个字典的解决方法
你的输入字符串是两个JSON字典直接拼接而成,没有合法分隔符,需要先修复格式再解析合并,下面是Python实现方案:
基础方案(重复键覆盖)
如果重复键只需要保留最后出现的值,用以下代码:
import json # 原始输入字符串 raw_str = '{"pr2":[2,"Hair Dryer(Fashion)","₹1499.00","home/images/hairdetyerxyz.png","2"],"pr5":[1,"Bowls(Season bowls )","₹499","home/images/balls_season.png","5"]}{"pr2":[2,"Hair Dryer(Fashion)","₹1499.00","home/images/hairdetyerxyz.png","2"],"pr5":[1,"Bowls(Season bowls )","₹499","home/images/balls_season.png","5"]}' # 修复JSON格式:将拼接的字典转为数组结构 fixed_json = '[' + raw_str.replace('}{', '},{') + ']' # 解析为字典列表 dict_list = json.loads(fixed_json) # 合并为单个字典 merged_dict = {} for d in dict_list: merged_dict.update(d) print(merged_dict)
进阶方案(保留重复键的所有值)
如果需要保留所有重复键的内容,将重复值存入列表,用以下代码:
import json raw_str = '{"pr2":[2,"Hair Dryer(Fashion)","₹1499.00","home/images/hairdetyerxyz.png","2"],"pr5":[1,"Bowls(Season bowls )","₹499","home/images/balls_season.png","5"]}{"pr2":[2,"Hair Dryer(Fashion)","₹1499.00","home/images/hairdetyerxyz.png","2"],"pr5":[1,"Bowls(Season bowls )","₹499","home/images/balls_season.png","5"]}' fixed_json = '[' + raw_str.replace('}{', '},{') + ']' dict_list = json.loads(fixed_json) merged_dict = {} for d in dict_list: for key, val in d.items(): if key in merged_dict: # 若键已存在,将值转为列表并追加新内容 if not isinstance(merged_dict[key], list): merged_dict[key] = [merged_dict[key]] merged_dict[key].append(val) else: merged_dict[key] = val print(merged_dict)
内容的提问来源于stack exchange,提问作者kartik prajapati
相关产品推荐
相关产品推荐

