make a list of multiple individual dictionaries in python?

Let's say I have a list:

l = [1, 7, 2, 4, 3, 2, 4, 1, 4, 3]

How would I loop through to make a list of multiple individual dictionaries?

newl = [{1:7}, {2:4}, {3:2}, {4:1}, {4:3}]

3 answers

  • answered 2018-11-08 05:30 sacul

    You can use this list comprehension:

    >>> [{l[i]:l[i+1]} for i in range(0,len(l),2)]
    [{1: 7}, {2: 4}, {3: 2}, {4: 1}, {4: 3}]
    

  • answered 2018-11-08 05:31 SpghttCd

    My approach would be to initialize the dicts within a list comprehension which iterates over both the even and the odd elements:

     l = [1, 7, 2, 4, 3, 2, 4, 1, 4, 3]
    
     newl = [{k: v} for k, v in zip(l[::2], l[1::2])]
    
     #  [{1: 7}, {2: 4}, {3: 2}, {4: 1}, {4: 3}]
    

    If performance counts, please note @Netwave 's comment: here two additional lists are created which can be avoided (see their answer here).

  • answered 2018-11-08 05:38 Netwave

    Another efficient way is to use iter:

    >>> l = [1, 7, 2, 4, 3, 2, 4, 1, 4, 3]
    >>> it = iter(l)
    >>> [{x:y} for x,y in zip(it, it)]
    [{1: 7}, {2: 4}, {3: 2}, {4: 1}, {4: 3}]
    

    Or use itertools.islice for efficient iteration and no extra memmory overhead:

    [{k: v} for k, v in zip(islice(l, 0, None, 2), islice(l, 1, None, 2))]