如何将元组列表转换为字典

evi*_*ive 3 python

我有一个元组列表,如下所示:

lst_of_tpls = [(1, 'test2', 3, 4),(11, 'test12', 13, 14),(21, 'test22', 23,24)]
Run Code Online (Sandbox Code Playgroud)

我想将它转换为字典,使它看起来像这样:

mykeys = ['ones', 'text', 'threes', 'fours']
mydict = {'ones': [1,11,21], 'text':['test2','test12','test22'], 
          'threes': [3,13,23], 'fours':[4,14,24]}
Run Code Online (Sandbox Code Playgroud)

我试图列举lst_of_tpls这样的:

mydict = dict.fromkeys(mykeys, [])
for count, (ones, text, threes, fours) in enumerate(lst_of_tpls):
    mydict['ones'].append(ones)
Run Code Online (Sandbox Code Playgroud)

但是这使得我希望在'ones'中看到的值也在其他"类别"中:

{'ones': [1, 11, 21], 'text': [1, 11, 21], 'threes': [1, 11, 21], 'fours': [1, 11, 21]}
Run Code Online (Sandbox Code Playgroud)

另外,我想保持mykeys灵活性.

Aja*_*234 6

您可以申请zip两次以找到合适的配对:

lst_of_tpls = [(1, 'test2', 3, 4),(11, 'test12', 13, 14),(21, 'test22', 23,24)]
mykeys = ['ones', 'text', 'threes', 'fours']
new_d = {a:list(b) for a, b in zip(mykeys, zip(*lst_of_tpls))}
Run Code Online (Sandbox Code Playgroud)

输出:

{
 'ones': [1, 11, 21],
 'text': ['test2', 'test12', 'test22'],
 'threes': [3, 13, 23],
 'fours': [4, 14, 24]
}
Run Code Online (Sandbox Code Playgroud)