将元组列表更改为字典(pythonic方式)

dre*_*ski 1 python sqlite dictionary tuples list

这更像是一个最佳实践问题.我创建的是完美的工作,但我很好奇是否有一个更短的方法来创建我当前的数据结构中的字典.

我正在从SQLite数据库中读取表格,数据作为元组列表返回.例如

[(49, u'mRec49', u'mLabel49', 1053, 1405406806822606L, u'1405406906822606'), 
(48, u'mRec48', u'mLabel48', 1330, 1405405806822606L, u'1405405906822606'), 
(47, u'mRec47', u'mLabel47', 1220, 1405404806822606L, u'1405404906822606')...
] 
Run Code Online (Sandbox Code Playgroud)

我想获取list-tuple结构的每一列,使其成为一个列表,从数据库中获取列名,并将其用作保存列表的键.后来我把字典变成了JSON.

这是我的功能,我抓了,它完成了工作,我不禁想知道是否有更好的方法来做到这一点.

def make_dict(columns, list_o_tuples):
    anary = {}
    for j, column in enumerate(columns):
        place = []
        for row in list_o_tuples:
            place.append(row[j])
        anary[column] = place
    return anary

make_dict(mDBTable.columns, mDBTable.get_table())
Run Code Online (Sandbox Code Playgroud)

注意:该函数不应关心其呈现的表,或表中的数字或行和列.

mgi*_*son 6

看来你想要转置list_o_tuples:

transpose = zip(*list_o_tuples)
Run Code Online (Sandbox Code Playgroud)

然后使用列名称将其压缩:

return dict(zip(columns, transpose))
Run Code Online (Sandbox Code Playgroud)