evilolive
evilolive

Reputation: 507

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_tplslike so:

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': [1, 11, 21], 'text': [1, 11, 21], 'threes': [1, 11, 21], 'fours': [1, 11, 21]}

Also, I would like to keep mykeys flexible.

Upvotes: 2

Views: 95

Answers (2)

Vlad Bezden
Vlad Bezden

Reputation: 89527

You can pass to dict tuples of (key, value), it's twice faster than use dictionary comprehension

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:

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

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71451

You can apply zip twice to find the proper pairings:

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]
}

Upvotes: 5

Related Questions