我有一个元组列表,像这样:
lst_of_tpls = [(1, 'test2', 3, 4),(11, 'test12', 13, 14),(21, 'test22', 23,24)]
我想将其转换为字典,使其看起来像这样:
mykeys = ['ones', 'text', 'threes', 'fours']
mydict = {'ones': [1,11,21], 'text':['test2','test12','test22'],
'threes': [3,13,23], 'fours':[4,14,24]}
我试图像这样枚举lst_of_tpls
:
mydict = dict.fromkeys(mykeys, [])
for count, (ones, text, threes, fours) in enumerate(lst_of_tpls):
mydict['ones'].append(ones)
但这会将我想在“一个”中看到的值也放入其他“类别”中:
{'ones': [1, 11, 21], 'text': [1, 11, 21], 'threes': [1, 11, 21], 'fours': [1, 11, 21]}
此外,我想保持mykeys
的灵活性。
答案 0 :(得分: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))}
输出:
{
'ones': [1, 11, 21],
'text': ['test2', 'test12', 'test22'],
'threes': [3, 13, 23],
'fours': [4, 14, 24]
}
答案 1 :(得分:1)
您可以传递(key,value)的dict元组,它比使用字典理解的速度快两倍
lst_of_tpls = [(1, "test2", 3, 4), (11, "test12", 13, 14), (21, "test22", 23, 24)]
mykeys = ["ones", "text", "threes", "fours"]
my_dict = dict(zip(mykeys, zip(*lst_of_tpls)))
输出:
{'ones': (1, 11, 21),
'text': ('test2', 'test12', 'test22'),
'threes': (3, 13, 23),
'fours': (4, 14, 24)}
Profiler示例:
lst_of_tpls = [(1, "test2", 3, 4), (11, "test12", 13, 14), (21, "test22", 23, 24)]
mykeys = ["ones", "text", "threes", "fours"]
def dict_comprehension():
return {a: list(b) for a, b in zip(mykeys, zip(*lst_of_tpls))}
def dict_generator():
return dict(zip(mykeys, zip(*lst_of_tpls)))
if __name__ == "__main__":
import timeit
funcs = (dict_comprehension, dict_generator)
for f in funcs:
result = timeit.timeit(f, number=10000, globals=globals())
print(f"{f.__name__}: {result:.5f}")
dict_comprehension: 0.05009
dict_generator: 0.02468