Python元组组成的列表转化为字典

虽然元组、列表不可以直接转化为字典,但下面的确是可行的,因为经常用python从数据库中读出的是元组形式的数据。

    # 原始数据
    rows = (('apollo', 'male', '164.jpeg'), ('apollo', 'male', ''))
    # 表头
    names = 'username gender pic'.split()
    # URL公共部分
    fs_url = 'http://www.baidu.com/'

    # 新数据列表
    L = []
    for e in rows:
        L1 = list(e)
        pic = e[2]
        if pic == '':
            L1[2] = "%suser_pic/default.jpg" % (fs_url)
        else:
            L1[2] = "%suser_pic/small_%s" % (fs_url, pic)
        L.append(L1)
    print L
    # 用zip组合列表套字典
    """
    [{'username': 'apollo', 'gender': 'male', 'pic': 'http://www.baidu.com/user_pic/small_164.jpeg'}, 
    {'username': 'apollo', 'gender': 'male', 'pic': 'http://www.baidu.com/user_pic/default.jpg'}]
    """
    data = [dict(zip(names, d)) for d in L]
    print data
原文地址:https://www.cnblogs.com/apollo1616/p/10429901.html