简体   繁体   中英

More Pythonic Way To Do This?

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.

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]

您可以使用 zip [dict(zip(range(len(tp)),tp))) for tp in tuple_list]

Map enumerate into the dictionary constructior for each tuple:

processed_tuple_list = [*map(dict,map(enumerate,tuple_list))]

[{0: 'a', 1: 'b', 2: 'c'}, {0: 'e', 1: 'f', 2: 'g'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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