Search code examples
pythonlistdictionarynestednested-lists

How to change list of dictionaries into list of lists where every list is a key,value pair?


I have a list of dictionaries (with multiple key, value pairs) in python, and I'm trying to make each dictionary into a list, where each key,value pair is also it's own list. For example: list = [{a: 1, b: 2, c: 3}, {d: 4, e: 5, f: 6}, {g: 7,h: 8,i: 9}] What i want it to output is: newlist = [[[a, 1], [b, 2], [c, 3]], [[d, 4][e, 5],[f, 6]], [[g, 7],[h, 8],[i, 9]]]

The only method i've found only lets me have a list where key, value pairs from different dictionaries are in one large list, but i need each dictionary to be a different list.


Solution

  • my_list = [{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6}, {'g': 7,'h': 8,'i': 9}]
    r = []
    for _ in my_list:
       r.append([[k,v] for k,v in _.items()])
    
    print(r)
    

    [[['a', 1], ['b', 2], ['c', 3]], [['d', 4], ['e', 5], ['f', 6]], [['g', 7], ['h', 8], ['i', 9]]]