python list of dicts - convert each key-value as a individual dict

user3206440 :

with a list like below that has one or more dicts

l = [{'b': 'h', 'c': (1,2)}, {'d': [0, 1], 'e': {'f': 2, 'g': 'i'} } ]

need to extract each key-value pair as an individual dict

Expected output

[{'b': 'h'}, {'c': (1,2)}, {'d': [0, 1]}, {'e': {'f': 2, 'g': 'i'} } ]

I have been trying to do this via list comprehension - the outer comprehension could be something like [ {k,v} for k, v in ?? - need some help in getting the inner comprehension.

Óscar López :

I believe this is what you're looking for - except that the order of the elements might be different, but that's to be expected when dealing with dictionaries:

lst = [{'b': 'h', 'c': (1,2)}, {'d': [0, 1], 'e': {'f': 2, 'g': 'i'}}]
[{k: v} for d in lst for k, v in d.items()]

=> [{'c': (1, 2)}, {'b': 'h'}, {'e': {'g': 'i', 'f': 2}}, {'d': [0, 1]}]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=173875&siteId=1