How to split list of lists to each list in list to one dictionary using python

I currently have this list:

a = [[ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo'],[ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo' ],[ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo']]

I want to convert it to this dictionary:

[{'abc': 'lalalla', 'appa': 'kdkdkdkd', 'kkakaka': 'oeoeoeo'},
 {'abc': 'lalalla', 'appa': 'kdkdkdkd', 'kkakaka': 'oeoeoeo'},
 {'abc': 'lalalla', 'appa': 'kdkdkdkd', 'kkakaka': 'oeoeoeo'}]

I have tried using dict along with split:

d = (dict(x.split('=') for s in a for x in s))

I am getting only one dictionary because of keys are same so I how can I get every list as one dictionary?

4 answers

  • answered 2018-07-11 03:31 user3483203

    Right now you are using dict on a flattened version of your list, but instead you need to use it on each sublist individually after splitting:

    a = [dict([i.split('=') for i in j]) for j in a]
    

    Results in:

    [{'abc': 'lalalla', 'appa': 'kdkdkdkd', 'kkakaka': 'oeoeoeo'},
     {'abc': 'lalalla', 'appa': 'kdkdkdkd', 'kkakaka': 'oeoeoeo'},
     {'abc': 'lalalla', 'appa': 'kdkdkdkd', 'kkakaka': 'oeoeoeo'}]
    

  • answered 2018-07-11 03:36 Snowy

    a = [[ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo'],[ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo'],[ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo']]
    d = [dict(x.split('=') for x in s) for s in a]
    

  • answered 2018-07-11 03:38 U9-Forward

    one. Your list a is invalid python syntax.

    two. inside each list in a, it contains strings so you have to split it by '=' two get the key and the value.

    a = [[ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo'],[ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo'],[ 'abc=lalalla', 'appa=kdkdkdkd', 'kkakaka=oeoeoeo']]
    print(list(map(lambda x: dict(zip([i.split('=')[0] for i in x],[i.split('=')[1] for i in x])),a)))
    

    Output:

    [{'abc': 'lalalla', 'appa': 'kdkdkdkd', 'kkakaka': 'oeoeoeo'}, {'abc': 'lalalla', 'appa': 'kdkdkdkd', 'kkakaka': 'oeoeoeo'}, {'abc': 'lalalla', 'appa': 'kdkdkdkd', 'kkakaka': 'oeoeoeo'}]
    

  • answered 2018-07-11 04:15 RafaelC

    Just to play around, you can also use numpy's np.core.defchararray.split and dict comprehension

    [{k:v for k,v in np.core.defchararray.split(lis,'=')} for lis in a]
    
    [{'abc': 'lalalla', 'appa': 'kdkdkdkd', 'kkakaka': 'oeoeoeo'},
     {'abc': 'lalalla', 'appa': 'kdkdkdkd', 'kkakaka': 'oeoeoeo'},
     {'abc': 'lalalla', 'appa': 'kdkdkdkd', 'kkakaka': 'oeoeoeo'}]