标签:
keyValueResult = {‘a‘: 1, ‘b‘: 2}
sendData = []
def set_push_format(ip):
data_format = {
"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 sendData
if __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‘}]
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‘}]
标签:
原文地址:http://www.cnblogs.com/felixzh/p/5885284.html