Search code examples
pythonpython-2.7dictionarydictionary-comprehension

Parsing list items and returning a dictionary using comprehension


I have a two-items list which I need to process. Those items are retrieved from a database, so the are actually header: value pairs but they are unparsed. They are strings separated by tabs, so the list looks like this:

my_list = ['header1\theader2\theader3\theader4', 'val1\tval2\tval3\tval4']

I need to create dict from the key - value pairs. Currently I do it with list comprehension:

keys = [k.strip() for k in my_list[0].split('\t')]
vals = [v.strip() for v in my_list[1].split('\t')]
return dict(zip(keys, vals))

I think there might be a way doing that using dict comprehension instead, but I couldn't get how. Is it possible to do parse the list items and return a dictionary with a one-liner or a more pythonic way?


Solution

  • I find the solution below the most elegant one:

    dict_comp = dict(zip(*map(lambda x: x.split('\t'), my_list)))
    print(dict_comp)  # -> {'header1': 'val1', 'header2': 'val2', 'header3': 'val3', 'header4': 'val4'}
    

    Alternatively, the lambda can be substituted by a generator expression:

    dict_comp = dict(zip(*(x.split('\t') for x in my_list)))
    

    and if the strings do not contain any spaces, it can be shortened even further to:

    dict_comp = dict(zip(*map(str.split, my_list)))  # kudos @Chris_Rands