移除重复字典并排序列表键对应值,嵌套字典递归访问后续技术问询
Hey there! Let's break down solutions for your two requirements clearly:
需求1:移除重复字典并对列表中各键对应的值排序
思路说明
由于字典是不可哈希类型,没法直接用集合去重,所以我们先把每个字典转换成排序后的键值对元组(这样相同内容的字典会变成完全一样的元组),通过集合去重后再转回字典。之后遍历每个字典,对每个键对应的列表值进行排序。
代码实现
def remove_duplicate_dicts_and_sort_values(dict_list): # 步骤1:去重:将字典转为可哈希的排序元组,用集合去重后转回字典 unique_tuples = {tuple(sorted(d.items())) for d in dict_list} unique_dicts = [dict(t) for t in unique_tuples] # 步骤2:对每个字典的键值进行排序 for d in unique_dicts: for key in d: if isinstance(d[key], list): d[key].sort() return unique_dicts # 示例用法 sample_list = [ {"a": [3,1,2], "b": "hello"}, {"a": [3,1,2], "b": "hello"}, # 重复字典 {"c": [5,4], "d": "world"} ] result = remove_duplicate_dicts_and_sort_values(sample_list) print(result)
输出结果
[{'a': [1, 2, 3], 'b': 'hello'}, {'c': [4, 5], 'd': 'world'}]
需求2:递归访问嵌套字典的路径与值并导出到CSV
思路说明
基于你提供的代码片段,我们需要完善visit_dict函数,实现递归遍历嵌套字典的所有键路径和对应的值,把这些数据收集后写入CSV文件。路径可以用.来连接各级键,方便清晰展示层级关系。
完整代码实现
import json import csv def visit_dict(d, path=None, results=None): # 初始化默认参数 if path is None: path = [] if results is None: results = [] for key, value in d.items(): current_path = path + [str(key)] if isinstance(value, dict): # 如果值是字典,递归遍历 visit_dict(value, current_path, results) else: # 如果值不是字典,记录路径和值 results.append((".".join(current_path), value)) return results # 读取JSON文件 json_sample = 'sample_dict.json' with open(json_sample, 'r') as json_file: json_data = json.load(json_file) items = json_data['sample_dict'] # 递归收集路径和值 data_rows = visit_dict(items) # 写入CSV文件 with open('sample_dict.csv', 'w', newline='') as csv_file: writer = csv.writer(csv_file) # 写入表头 writer.writerow(["Path", "Value"]) # 写入数据行 writer.writerows(data_rows)
代码解释
visit_dict函数通过递归遍历嵌套字典:- 每次遇到字典类型的值,就把当前键加入路径,继续递归;
- 遇到非字典值,就把拼接好的路径(用
.分隔)和对应值存入结果列表。
- 用
with语句处理文件,确保文件正确关闭; - 最后把收集到的路径和值写入CSV,表头为
Path和Value,清晰展示每个值的层级位置。
内容的提问来源于stack exchange,提问作者cheebdragonite
相关产品推荐
相关产品推荐

