如何在Python中从字典列表创建嵌套字典?
实现字典列表到嵌套字典的转换
没问题,我来帮你搞定这个嵌套字典的构建需求。首先得明确:你给出的示例结构存在一个小隐患——如果一个国家有多个家族,单独的yrs键会被最后处理的家族年份覆盖。所以更合理的结构应该是让每个家族自己包含君主列表和对应的统治年份区间,下面是具体的实现方案:
代码实现
# 先修正你的输入格式(原输入是字典套字典,正确格式应为列表套字典) data1 = [ {"nm": "Oliver Cromwell", "cty": "United Kingdom", "hse": "Commonwealth", "yrs": "1653-1658"}, {"nm": "Richard Cromwell", "cty": "United Kingdom", "hse": "Commonwealth", "yrs": "1658-1659"}, {"nm": "Charles II", "cty": "United Kingdom", "hse": "House of Stuart", "yrs": "1660-1685"}, # 可继续添加更多君主条目 ] # 初始化最终结果字典 nested_dict = {} for monarch in data1: # 提取当前君主的核心信息 country = monarch["cty"] house = monarch["hse"] name = monarch["nm"] years = monarch["yrs"] # 第一步:确保国家存在于外层字典,不存在则创建空字典 if country not in nested_dict: nested_dict[country] = {} # 第二步:确保家族存在于对应国家的字典中,初始化名字列表和年份字段 if house not in nested_dict[country]: nested_dict[country][house] = {"names": [], "yrs": ""} # 将君主名字添加到对应家族的列表中 nested_dict[country][house]["names"].append(name) # 合并同一家族的统治年份区间:取最早开始时间和最晚结束时间 current_yrs = nested_dict[country][house]["yrs"] if not current_yrs: nested_dict[country][house]["yrs"] = years else: curr_start, curr_end = current_yrs.split("-") entry_start, entry_end = years.split("-") new_start = min(curr_start, entry_start) new_end = max(curr_end, entry_end) nested_dict[country][house]["yrs"] = f"{new_start}-{new_end}" # 打印结果查看 print(nested_dict)
代码解释
- 层级构建:从空字典开始,逐层检查国家、家族的键是否存在,不存在则创建对应空结构,避免
KeyError。 - 名字收集:自动将同一家族的君主名字归集到对应的列表中。
- 年份合并:针对同一家族的多位君主,自动合并在位年份,生成该家族完整的统治时间区间。
运行后会生成如下结构(更清晰且无键冲突):
{ "United Kingdom": { "Commonwealth": { "names": ["Oliver Cromwell", "Richard Cromwell"], "yrs": "1653-1659" }, "House of Stuart": { "names": ["Charles II"], "yrs": "1660-1685" } } }
如果你坚持要示例中的格式(单家族场景)
如果你的场景只处理单个家族,也可以用以下代码,但注意多家族时yrs键会被最后一条数据覆盖:
result = {} for monarch in data1: country = monarch["cty"] house = monarch["hse"] name = monarch["nm"] years = monarch["yrs"] if country not in result: result[country] = {} result[country].setdefault(house, []).append(name) result[country]["yrs"] = years # 多家族场景下会被覆盖,谨慎使用
内容的提问来源于stack exchange,提问作者user8910400
相关产品推荐
相关产品推荐

