如何拆分Python字典的值并提取指定键及对应次值
Python字典处理需求及实现
原始数据
data = { "key1": ["<A><B>"], "key2": ["<C><D>"], "key3": ["<A><F>"], # ... 更多键值对 }
处理目标
- 转换为新字典,将每个值列表中的拼接字符串拆分为独立标签元素:
new_dict = { "key1": ["<A>", "<B>"], "key2": ["<C>", "<D>"], "key3": ["<A>", "<F>"], # ... 更多键值对 }
- 提取所有首值为
<A>的键,组成列表:
A_as_first_value = ["key1", "key3"]
- 提取上述键对应的第二个值,组成列表:
second_values_ = ["<B>", "<F>"]
实现代码
步骤1:生成拆分后的新字典
遍历原始字典,将每个值中的拼接字符串按标签拆分(假设每个字符串均为两个<X>格式标签拼接而成):
data = { "key1": ["<A><B>"], "key2": ["<C><D>"], "key3": ["<A><F>"] } new_dict = {} for key, val_list in data.items(): combined_str = val_list[0] # 找到第二个<的位置进行拆分 split_pos = combined_str.index("<", 1) new_dict[key] = [combined_str[:split_pos], combined_str[split_pos:]]
步骤2:筛选首值为的键
A_as_first_value = [k for k, v in new_dict.items() if v[0] == "<A>"]
步骤3:提取对应第二个值
second_values_ = [new_dict[k][1] for k in A_as_first_value]
测试输出
print(new_dict) # 输出: {'key1': ['<A>', '<B>'], 'key2': ['<C>', '<D>'], 'key3': ['<A>', '<F>']} print(A_as_first_value) # 输出: ['key1', 'key3'] print(second_values_) # 输出: ['<B>', '<F>']
内容的提问来源于stack exchange,提问作者Pybubb
相关产品推荐
相关产品推荐

