python list append方法


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'}]

方法一,使用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循環的操作都是在更新這個對象的keyvalue,自始至終就這一個對象,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]: r Out[3]: [{'description': 't1', 'title': 'd1'}, {'description': 't2', 'title': 'd2'}

方法一的循環中,post_dict始終指向的是同一個對象。 在for循環中,使用匿名對象就可以了:

 
for row in cur: posts.append({'title':row[0],'description':row[1]})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM