问题:将数据库中查出的数据(列表中包含元组)转换为列表中字典。原数据结构,从数据库查出:cur=[("t1","d1"),("t2","d2")]转换后数据结构:[{'description':'d1','title':'t1'},{'description':'d2','title':'t2'}]方法一,使用append,出现错误结果pythoncur=[("t1","d1"),("t2","d2")]post_dict={}posts=[]forrowincur:post_dict['title']=row[0]post_dict['description']=row[1]print"post_dict:",post_dictposts.append(post_dict)print"posts:",posts方法一运行结果:pythonpost_dict:{'description':'d1','title':'t1'}posts:[{'description':'d1','title':'t1'}]post_dict:{'description':'d2','title':'t2'}posts:[{'description':'d2','title':'t2'},{'description':'d2','title':'t2'}]方法二,使用列表解析,结果正常pythoncur=[("a","a1"),("b","b1")]posts=[]posts=[dict(title=row[0],description=row[1])forrowincur]print"posts:",posts方法二运行结果,正常pythonposts:[{'description':'d1','title':'t1'},{'description':'d2','title':'t2'}]
月关宝盒
Helenr
相关分类