简体   繁体   English

将列表字典转换为字典列表

[英]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.使用zip同时迭代两个列表。 Use a dict constructor to create individual dictionaries, inside a list comprehension to handle automatically looping.使用dict constructor创建单独的字典,在list comprehension中自动处理循环。

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:在许多 NoSQL 引擎中,数据通常以嵌套方式存储,对于您的情况,它将是:

{'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这提供了一种通过 ID 访问数据的有效方法

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 ,这是转换格式的代码:此代码是通用的 - 意味着您不必指定密钥,在这种情况下: usernamepassword

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!'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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