简体   繁体   English

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

[英]How do I convert a list of tuples to a dictionary

I have a list of tuples, like so: 我有一个元组列表,如下所示:

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

And I would like to convert it to a dictionary so that it looks like this: 我想将它转换为字典,使它看起来像这样:

mykeys = ['ones', 'text', 'threes', 'fours']
mydict = {'ones': [1,11,21], 'text':['test2','test12','test22'], 
          'threes': [3,13,23], 'fours':[4,14,24]}

I have tried to enumerate the lst_of_tpls like so: 我试图像这样枚举lst_of_tpls

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

but this puts the values I would like to see in 'ones' also in the other "categories": 但是这使得我希望在'ones'中看到的值也在其他“类别”中:

{'ones': [1, 11, 21], 'text': [1, 11, 21], 'threes': [1, 11, 21], 'fours': [1, 11, 21]}

Also, I would like to keep mykeys flexible. 另外,我想保持mykeys灵活性。

You can apply zip twice to find the proper pairings: 您可以应用两次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))}

Output: 输出:

{
 'ones': [1, 11, 21],
 'text': ['test2', 'test12', 'test22'],
 'threes': [3, 13, 23],
 'fours': [4, 14, 24]
}

You can pass to dict tuples of (key, value), it's twice faster than use dictionary comprehension 你可以传递给(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)))

Output: 输出:

{'ones': (1, 11, 21),
 'text': ('test2', 'test12', 'test22'),
 'threes': (3, 13, 23),
 'fours': (4, 14, 24)}

Profiler example: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM