KingFish
KingFish

Reputation: 9153

Split a dictionary into a list of dictionaries

I'm sure this is very easy:

If I have the following:

 mydict = { 'key1': 'value1', 'key2': 'value2', ... , 'keyn': 'valuen' }

How can I end up w/ a list such as:

 result = [ { 'key1': 'value1'}, { 'key2': 'value2' }, ...., 'keyn': 'valuen' }]

Upvotes: 0

Views: 2836

Answers (2)

oleg
oleg

Reputation: 4182

I think the easiest way to do this is list comprehension

mydict = { 'key1': 'value1', 'key2': 'value2', ... , 'keyn': 'valuen' }
new_list = [{k: v} for k, v in mydict.iteritems()]

or not so interesting version

map(lambda x, y: {x: y}, mydict.iteritems())

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798536

result = [{k: v} for (k, v) in mydict.iteritems()]

Upvotes: 4

Related Questions