Home > Blockchain >  More Pythonic Way To Do This?
More Pythonic Way To Do This?

Time:11-07

I have a list of tuples and I want to convert it to a list of dictionaries where, for each tuple, the dictionary keys are the index in a tuple and the value is the tuple entry in that index.

For example if tuple_list=[('a','b','c'), ('e','f','g')] then the goal is to have processed_tuple_list = [{0:'a',1:'b',2:'c'},{0:'e',1:'f',2:'g'}]

My current solution is to have a function

def tuple2dict(tup):
    x = {}
    for j in range(len(tup)):
        x[j]=tup[j]
    return x

and then call [tuple2dict(x) for x in tuple_list]. I suspect there is a list-comprehension way to do this and I initially tried to do

[{j:x[j]} for x in tuple_list for j in range(len(x))]

but this just gave me a list of [{0:'a'},{1:'b'},...]. Any advice on a more pythonic way to do this would be much appreciated.

CodePudding user response:

You can create dict for each tuple in list like below:

>>> tuple_list=[('a','b','c'), ('e','f','g')]
# Expanded solution for more explanation
>>> [{idx: val for idx, val in enumerate(tpl)} for tpl in tuple_list]
[{0: 'a', 1: 'b', 2: 'c'}, {0: 'e', 1: 'f', 2: 'g'}]

By thanks @ddejohn shortest approach:

>>> [dict(enumerate(t)) for t in tuple_list]

CodePudding user response:

you can use zip [dict(zip(range(len(tp)),tp))) for tp in tuple_list]

  • Related