简体   繁体   English

从键列表和多个值创建字典

[英]Create dictionary from lists of keys and multiple values

I have two lists: 我有两个清单:

header = ["Name", "Age"]
detail = ["Joe", 22, "Dave", 43, "Herb", 32]

And would like to create a list of dictonaries like this: 并希望创建一个像这样的dictonaries列表:

[{"Name": "Joe", "Age": 22}, {"Name": "Dave", "Age": 32}, {"Name": "Herb", "Age": 32}]

This method zip gets me partially there, but only adds the first set of values to the dictionary: 这个方法zip部分地在那里,但只将第一组值添加到字典中:

>>> dict(zip(header, detail))
{'Age': 22, 'Name': 'Joe'}

How can I output as one dictionary for all values in the detail list? 如何输出detail列表中所有值的一个字典? I found this answer , but this depends on detail containing nested lists. 我找到了这个答案 ,但这取决于包含嵌套列表的detail

>>> detail = ["Joe", 22, "Dave", 43, "Herb", 32]
>>> d = dict(zip(detail[::2], detail[1::2]))
>>> d
{'Herb': 32, 'Dave': 43, 'Joe': 22}

For your new/edited question: 对于您的新/编辑问题:

>>> d = [dict(zip(header, items)) for items in zip(detail[::2],detail[1::2])]
>>> d
[{'Age': 22, 'Name': 'Joe'}, {'Age': 43, 'Name': 'Dave'}, {'Age': 32, 'Name': 'H
erb'}]

Here's one way to get it: 这是获得它的一种方法:

header = ["Name", "Age"]
detail = ["Joe", 22, "Dave", 43, "Herb", 32]
data_iter = iter(detail)
collated = []
while True:
    next_data = zip(header, data_iter)
    if not next_data:
        break
    collated.append(dict(next_data))

output is 输出是

[{'Age': 22, 'Name': 'Joe'},
 {'Age': 43, 'Name': 'Dave'},
 {'Age': 32, 'Name': 'Herb'}]

This version has the advantage that you don't need to change the code if you change the number of headers. 此版本的优点是,如果更改标题数,则无需更改代码。

For such tasks I prefer functional approach. 对于这样的任务我更喜欢功能方法。

Here is a recipe for grouper: 这是石斑鱼的食谱

def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

By using it, we may advance trough detail by groups of 2 : 通过使用它,我们可以通过2组来推进detail

>>> groups = grouper(len(header),detail)
>>> list(groups)
[('Joe', 22), ('Dave', 43), ('Herb', 32)]

And then we can use this iterator to create dictionaries as you need: 然后我们可以使用这个迭代器来根据需要创建字典:

>>> [dict(zip(header,group)) for group in groups]
[{'Age': 22, 'Name': 'Joe'}, {'Age': 43, 'Name': 'Dave'}, {'Age': 32, 'Name': 'Herb'}]

To clarify, zip(header,group) gives this: 为了澄清, zip(header,group)给出了:

>>> zip(["Name", "Age"],('Joe', 22))
[('Name', 'Joe'), ('Age', 22)]

And summoning dict constructor gives this: 并召唤dict构造函数给出:

>>> dict([('Name', 'Joe'), ('Age', 22)])
{'Age': 22, 'Name': 'Joe'}
>>> header = ["Name", "Age"]
>>> detail = ["Joe", 22, "Dave", 43, "Herb", 32]
>>> [dict(zip(header,detail[i:i+2])) for i in range(0,len(detail),2)]
[{'Age': 22, 'Name': 'Joe'}, {'Age': 43, 'Name': 'Dave'}, {'Age': 32, 'Name': 'Herb'}]`

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

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