Python有序字典列表拆包重排:代码输出None原因排查
问题分析与修复方案
嘿,你的代码输出None是因为好几处逻辑漏洞,我来帮你理清楚并修正:
你的代码里的核心问题
return_values_lists提前终止:这个方法里的while循环刚执行第一次就return了,只能拿到第一个OrderedDict的数据,根本没法遍历所有元素。zip用法完全错误:names是单个字符串(比如'Tel saki'),data_sets是装着dict_values的列表,用zip(names, data_sets)会把字符串拆成单个字符和data_sets的元素重复配对,完全偏离你想要的结果。create_new_dicts逻辑混乱:不仅while循环同样一执行就return,还把局部变量data和全局的data搞混了,那个类变量index完全没必要,还会导致多次调用时状态乱掉。- 未处理遍历完成的边界情况:当
index超过data长度后,return_values_lists没有返回值,后续赋值会报错,最终就可能输出None。
修正后的代码
根据你的需求——把每个OrderedDict的Name值作为键,原字典作为值,返回对应的结构——我们可以把代码简化很多,完全不需要那些复杂的类变量和无效循环:
方案1:返回一个大字典(键为Name值,值为对应OrderedDict)
from collections import OrderedDict data = [ OrderedDict([('Name', 'Tel saki'), ('Area', '210'), ('Latitude', 32.866477), ('Longitude', 35.830773), ('elevation', 481), ('date_added', '13-03-2020')]), OrderedDict([('Name', 'Mitzphe shelagim'), ('Area', '210'), ('Latitude', 33.30445), ('Longitude', 35.797814), ('elevation', 2110), ('date_added', '29-03-2020')]), OrderedDict([('Name', 'Mitzphe adi'), ('Area', '769'), ('Latitude', 33.2253981), ('Longitude', 35.5495681), ('elevation', 680), ('date_added', '17-03-2020')]), OrderedDict([('Name', 'Nhahal Oz'), ('Area', '300'), ('Latitude', 31.4762228), ('Longitude', 34.4974832), ('elevation', 68), ('date_added', '30-03-2020')]), OrderedDict([('Name', '105'), ('Area', '210'), ('Latitude', 33.220439), ('Longitude', 35.808097), ('elevation', 1127), ('date_added', '07-04-2020')]), OrderedDict([('Name', 'Ifthah'), ('Area', '300'), ('Latitude', 31.5487777), ('Longitude', 34.4873539), ('elevation', 29), ('date_added', '08-04-2020')]) ] class RepackDictionaries: @classmethod def create_new_dicts(cls): # 直接遍历所有OrderedDict,用Name字段的值作为键,原字典作为值 result_dict = {} for item in data: # 直接通过键取Name值,比取第一个值更可靠(万一OrderedDict结构变动也不怕) name_key = item['Name'] result_dict[name_key] = item return result_dict if __name__ == '__main__': print(RepackDictionaries.create_new_dicts())
方案2:返回列表(每个元素是{Name值: 原OrderedDict}的小字典)
如果你确实需要返回列表(符合你描述的“返回新列表”),改成这样就行:
from collections import OrderedDict # data定义和上面一致 class RepackDictionaries: @classmethod def create_new_dicts(cls): result_list = [] for item in data: name_key = item['Name'] result_list.append({name_key: item}) return result_list if __name__ == '__main__': print(RepackDictionaries.create_new_dicts())
为啥你的代码输出None?
当return_values_lists里的index增长到等于data长度后,再调用它时,while循环不会执行,方法默认返回None。这时候names, data_sets = cls.return_values_lists()会尝试解构None直接报错;就算没报错,前面的zip处理逻辑完全错误,最后create_new_dicts也没法返回有效结果,最终就输出None了。
内容的提问来源于stack exchange,提问作者user12177026
相关产品推荐
相关产品推荐

