Turn a dictionary of lists in to a list of dictionaries in Python 2.7

I have this

original = {
   "state_id": "1,2",
   "name": "A,B"
}

I can easily turn in to this

original_splitted = {k: v.split(',') for k, v in original.iteritems()}
{
   "state_id": ['1', '2'],
   "name": ['A' ,'B']
}

But what I want is this:

[
    {"state_id": '1', "name": "A"}, 
    {"state_id": '2', "name": "B"} 
]

I am looking for a cool "one-liner" comprehension magic to achieve this (avoiding the use of large nested loops)

Upvotes: 2

Views: 80

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250901

How about a 2-liner using zip(*) and a list comprehension:

>>> vals = zip(*(x.split(',') for x in original.itervalues()))
>>> [dict(zip(original, v)) for v in vals]
[{'state_id': '1', 'name': 'A'}, {'state_id': '2', 'name': 'B'}]

Upvotes: 4

Related Questions