如何在Python中将字典转换为指定格式的字典列表?
解决字典格式转换问题:从键值对字典到指定结构的字典列表
首先,先明确你的需求:你有一个映射英文数字到阿拉伯数字的字典,想要把它转换成一个包含多个小字典的列表,每个小字典都有eng和math两个键。
你的原字典
digit = { 'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4, 'five' : 5 }
目标格式
new_dict = [{'eng':'one','math': 1}, {'eng':'two','math': 2}, {'eng':'three','math': 3}, {'eng':'four','math': 4}, {'eng':'five','math': 5} ]
你遇到的问题
你尝试的代码出现了AttributeError: 'str' object has no attribute 'items'错误,我们先看看你写的代码:
digit = { 'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4, 'five' : 5 } new_dict={'eng':'','math':''} for nest_key,nest_val in new_dict.items(): for (key,value),(k,v) in nest_val.items(), digit.items(): if nest_val['eng'] == '': nest_val.update({k:v}) nest_val.append({k:v}) print(new_dict)
错误原因分析
- 初始对象类型错误:你把
new_dict定义成了单个字典,但实际上你需要的是一个字典列表,这是核心方向错误。 - 循环逻辑错误:内层循环中,
nest_val是new_dict里的value(也就是空字符串''),字符串没有items()方法,这就是报错的直接原因。 - 方法使用错误:你试图给字典调用
append()方法,但append()是列表的专属方法,字典根本没有这个方法,哪怕前面的错误解决了,这里也会报错。
正确的解决方案
这里提供两种简单有效的实现方式:
方式一:列表推导式(最简洁)
这是Python中处理这类转换最常用的方式,一行代码就能搞定:
digit = { 'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4, 'five' : 5 } new_dict = [{'eng': key, 'math': value} for key, value in digit.items()] print(new_dict)
方式二:普通for循环(更易理解)
如果刚接触Python,用普通循环更直观,能清晰看到每一步的操作:
digit = { 'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4, 'five' : 5 } new_dict = [] # 先初始化一个空列表,用来存放每个小字典 for eng_word, num in digit.items(): # 每次循环创建一个符合要求的小字典,添加到列表中 new_dict.append({'eng': eng_word, 'math': num}) print(new_dict)
这两种方式运行后,都会输出你想要的目标格式。它们的核心逻辑都是遍历原字典的每一组键值对,把键对应到eng,值对应到math,生成新的小字典后收集到列表里。
内容的提问来源于stack exchange,提问作者Rex5
相关产品推荐
相关产品推荐

