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.
CodePudding user response:
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]]]
CodePudding user response:
Please do not use list
as an identifier or variable name.
l = [{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6}, {'g': 7,'h': 8,'i': 9}]
[[list(x) for x in l[y].items()] for y in range(len(l))]
#output
[[['a', 1], ['b', 2], ['c', 3]], [['d', 4], ['e', 5], ['f', 6]], [['g', 7], ['h', 8], ['i', 9]]]