如何将含键值元素的列表转换为指定格式的Python字典?
列表转指定格式字典的实现方法
给定如下形式的列表:
List = ["key1", "key2", "value2", "value2", "key3", "value3", "value3", "key4", "value4"]
需要转换为目标字典:
{"key1": [], "key2": ["value2", "value2"], "key3": ["value3", "value3"], "key4": ["value4"]}
实现步骤
核心思路就是遍历列表,跟踪当前处理的键,把后续元素都加到该键的列表里,直到遇到下一个键为止。具体代码如下:
result_dict = {} current_key = None for item in List: # 这里根据键的特征判断,示例中键以'key'开头,可根据实际情况修改判断逻辑 if item.startswith('key'): current_key = item result_dict[current_key] = [] else: if current_key is not None: result_dict[current_key].append(item) # 输出结果 print(result_dict)
代码说明
- 初始化空字典
result_dict存储最终结果,current_key用来记录当前要添加值的键 - 遍历列表时,遇到键就更新
current_key,并在字典中为这个键创建一个空列表 - 遇到值时,就把它追加到
current_key对应的列表中 - 因为
key1之后直接遇到key2,所以它的列表保持为空,符合需求
内容的提问来源于stack exchange,提问作者Minda
相关产品推荐
相关产品推荐

