pythonlistdictionary

List of dicts to/from dict of lists


I want to change back and forth between a dictionary of (equal-length) lists:

DL = {'a': [0, 1], 'b': [2, 3]}

and a list of dictionaries:

LD = [{'a': 0, 'b': 2}, {'a': 1, 'b': 3}]

Solution

  • Perhaps consider using numpy:

    import numpy as np
    
    arr = np.array([(0, 2), (1, 3)], dtype=[('a', int), ('b', int)])
    print(arr)
    # [(0, 2) (1, 3)]
    

    Here we access columns indexed by names, e.g. 'a', or 'b' (sort of like DL):

    print(arr['a'])
    # [0 1]
    

    Here we access rows by integer index (sort of like LD):

    print(arr[0])
    # (0, 2)
    

    Each value in the row can be accessed by column name (sort of like LD):

    print(arr[0]['b'])
    # 2