問題:將數(shù)據(jù)庫中查出的數(shù)據(jù)(列表中包含元組)轉(zhuǎn)換為列表中字典。
原數(shù)據(jù)結(jié)構(gòu),從數(shù)據(jù)庫查出:
cur = [("t1", "d1"), ("t2", "d2")]
轉(zhuǎn)換后數(shù)據(jù)結(jié)構(gòu):
[{'description': 'd1', 'title': 't1'}, {'description': 'd2', 'title': 't2'}]
方法一,使用append, 出現(xiàn)錯誤結(jié)果
pythoncur = [("t1", "d1"), ("t2", "d2")]
post_dict = {}
posts = []
for row in cur:
post_dict['title'] = row[0]
post_dict['description'] = row[1]
print "post_dict:",post_dict
posts.append(post_dict)
print "posts:",posts
方法一運(yùn)行結(jié)果:
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'}]
方法二,使用列表解析,結(jié)果正常
pythoncur = [("a", "a1"), ("b", "b1")]
posts = []
posts = [dict(title=row[0], description=row[1]) for row in cur]
print "posts:",posts
方法二運(yùn)行結(jié)果,正常
pythonposts: [{'description': 'd1', 'title': 't1'}, {'description': 'd2', 'title': 't2'}]
2 回答

蕭十郎
TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超13個贊
方法一中,你的post_dict
是一個字典對象,for
循環(huán)的操作都是在更新這個對象的key
和value
,自始至終就這一個對象,append
多少次都一樣。
把字典對象放在循環(huán)內(nèi)創(chuàng)建即可:
python
cur = [("t1", "d1"), ("t2", "d2")] posts = [] for row in cur: post_dict = {} post_dict['title'] = row[0] post_dict['description'] = row[1] print "post_dict:",post_dict posts.append(post_dict) print "posts:",posts
優(yōu)先考慮列表解析,另,本例的tupel列表可以用循環(huán)解包,大致如下:
python
In [1]: cur = [("t1", "d1"), ("t2", "d2")] In [2]: r = [{'description': description, 'title': title} for description, title in cur] In [3]: r Out[3]: [{'description': 't1', 'title': 'd1'}, {'description': 't2', 'title': 'd2'}]

猛跑小豬
TA貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個贊
方法一的循環(huán)中,post_dict始終指向的是同一個對象。
在for循環(huán)中,使用匿名對象就可以了:
for row in cur:
posts.append({'title':row[0],'description':row[1]})
添加回答
舉報(bào)
0/150
提交
取消