如何根据键名中的数字序号将Python字典拆分为多个子字典
注意事项
不要使用dict作为变量名,这是Python内置关键字,会覆盖原有字典类的功能,建议将原字典重命名为original_dict这类自定义名称。
实现代码
如果你给出的原字典键格式固定为属性名 序号(属性名和序号用空格分隔),可以直接用如下最简实现:
original_dict = { "name 1": "abc..", "location 1": "abc..", "name 2": "abc..", "location 2": "abc" } output_dict = {} for key, value in original_dict.items(): # 提取键末尾的数字序号 num = key.split()[-1] sub_dict_key = f"dict {num}" # 子字典不存在则初始化 if sub_dict_key not in output_dict: output_dict[sub_dict_key] = {} # 写入键值对到对应子字典 output_dict[sub_dict_key][key] = value
如果你的键名格式更复杂(比如序号和其他字符没有空格分隔、序号出现在键名中间),可以用正则表达式提取数字部分,替换上述num的取值逻辑即可:
import re # 提取键中第一个出现的连续数字作为序号 num = re.search(r'\d+', key).group()
输出验证
运行代码后打印output_dict,得到的结果符合要求:
{ 'dict 1': {'name 1': 'abc..', 'location 1': 'abc..'}, 'dict 2': {'name 2': 'abc..', 'location 2': 'abc'} }
内容的提问来源于stack exchange,提问作者Nicola Pilia
相关产品推荐
相关产品推荐

