简体   繁体   中英

Convert a dictionary of lists into a list of dictionaries

I have the following Dictionary Object:

Input = {'userName': ['psrr_api@auto-grid.com', 'ps_api1@auto-grid.com'],
         'password': ['Everseeource2016!', 'Eversource2016!']}

Which will then result in this specific output:

output = [{'UserName':'ps_api@auto-grid.com','password': 'Eversource2016!'},
          {'userName':'ps_api1@auto-grid.com','password':'Eversource2016!'}]

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

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': ['psrr_api@auto-grid.com', 'ps_api1@auto-grid.com'], 'password': ['Everseeource2016!', 'Eversource2016!']}

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

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

{'ID_1':
    {
    'username':'psrr_api@auto-grid.com',
    'password': 'Everseeource2016'
    },
'ID_2':{
    'username':'ps_api1@auto-grid.com',
    '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

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': ['psrr_api@auto-grid.com', 'ps_api1@auto-grid.com'],
         'password': ['Everseeource2016!', 'Eversource2016!']}

for i in output:
    print(i)

Output:

{'userName': 'psrr_api@auto-grid.com', 'password': 'Everseeource2016!'}
{'userName': 'ps_api1@auto-grid.com', 'password': 'Eversource2016!'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM