首页 > 代码库 > python list append方法
python list append方法
keyValueResult = {‘a‘: 1, ‘b‘: 2}sendData = http://www.mamicode.com/[]"endpoint": "test-endpoint", "metric": "test-metric", "timestamp": 54, "step": 60, "value": 1, "counterType": "GAUGE", "tags": "", } # print keyValueResult for key_value in keyValueResult: data_format = data_format.copy() # print key_value data_format[‘endpoint‘] = ip data_format[‘metric‘] = key_value data_format[‘value‘] = keyValueResult.get(key_value) print ‘data_format:‘ + key_value print data_format # 字典赋值给列表,构建JSON文件格式 sendData.append(data_format) print ‘sendData:‘ + key_value print sendDataif __name__ == "__main__": set_push_format(‘192.168.137.10‘) print ‘final‘ print sendData
该句必须加上,不然append的全是同一个字典!
别人遇到的类似问题
问题:将数据库中查出的数据(列表中包含元组)转换为列表中字典。
原数据结构,从数据库查出:
cur = [("t1", "d1"), ("t2", "d2")]
转换后数据结构:
[{‘description‘: ‘d1‘, ‘title‘: ‘t1‘}, {‘description‘: ‘d2‘, ‘title‘: ‘t2‘}]
方法一,使用append, 出现错误结果
cur = [("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
方法一运行结果:
post_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‘}]
方法二,使用列表解析,结果正常
cur = [("a", "a1"), ("b", "b1")] posts = []posts = [dict(title=row[0], description=row[1]) for row in cur]print "posts:",posts
方法二运行结果,正常
posts: [{‘description‘: ‘d1‘, ‘title‘: ‘t1‘}, {‘description‘: ‘d2‘, ‘title‘: ‘t2‘}]
采纳
方法一中,你的post_dict
是一个字典对象,for
循环的操作都是在更新这个对象的key
和value
,自始至终就这一个对象,append
多少次都一样。
把字典对象放在循环内创建即可:
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
优先考虑列表解析,另,本例的tupel列表可以用循环解包,大致如下:
In [1]: cur = [("t1", "d1"), ("t2", "d2")]In [2]: r = [{‘description‘: description, ‘title‘: title} for description, title in cur]In [3]: rOut[3]: [{‘description‘: ‘t1‘, ‘title‘: ‘d1‘}, {‘description‘: ‘t2‘, ‘title‘: ‘d2‘}
方法一的循环中,post_dict始终指向的是同一个对象。 在for循环中,使用匿名对象就可以了:
for row in cur: posts.append({‘title‘:row[0],‘description‘:row[1]})
python list append方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。