Gupta
Gupta

Reputation: 10358

Convert a dictionary of lists into a list of dictionaries

I have the following Dictionary Object:

Input = {'userName': ['[email protected]', '[email protected]'],
         'password': ['Everseeource2016!', 'Eversource2016!']}

Which will then result in this specific output:

output = [{'UserName':'[email protected]','password': 'Eversource2016!'},
          {'userName':'[email protected]','password':'Eversource2016!'}]

I'm not sure how I would approach this problem and any help would be appreciated.

Upvotes: 3

Views: 1937

Answers (3)

Stephen Rauch
Stephen Rauch

Reputation: 49784

And if by chance you need a variable number of keys, you can generalize to:

Code:

keys = [(k,) * len(data[k]) for k in data.keys()]
data_vals = [data[k] for k in data.keys()]
output = [dict(kv) for kv in
          (zip(*pairs) for pairs in zip(zip(*keys), zip(*data_vals)))]

Test Code:

data = {'userName': ['[email protected]', '[email protected]'],
         'password': ['Everseeource2016!', 'Eversource2016!']}

for i in output:
    print(i)

Output:

{'userName': '[email protected]', 'password': 'Everseeource2016!'}
{'userName': '[email protected]', 'password': 'Eversource2016!'}

Upvotes: 1

Devi Prasad Khatua
Devi Prasad Khatua

Reputation: 1235

In many NoSQL engines data is generally stored in a nested way, for your case it would be:

{'ID_1':
    {
    'username':'[email protected]',
    'password': 'Everseeource2016'
    },
'ID_2':{
    'username':'[email protected]',
    'password': 'Eversource2016!'
    }
}

This provides an efficient way to access the data through the ID's

More Examples

Here's the code for converting the format: This code is generic - means you don't have to specify the keys, in this case: username and password,

from collections import defaultdict
data = defaultdict(dict)
for idx in range(len(Input.values()[0])):
    for key in Input.keys():
        data['ID_'+str(idx)].update({key: Input[key][idx]})
print data

Upvotes: 2

aghast
aghast

Reputation: 15300

Use a zip to iterate over two lists as the same time. Use a dict constructor to create individual dictionaries, inside a list comprehension to handle automatically looping.

Input = {'userName': ['[email protected]', '[email protected]'], 'password': ['Everseeource2016!', 'Eversource2016!']}

Output = [ {'UserName':u, 'password':p} for u,p in zip(Input['userName'], Input['password']) ]

Upvotes: 4

Related Questions