gpt4 book ai didi

python - 如何从具有不同长度列表的字典创建字典列表

转载 作者:行者123 更新时间:2023-12-03 00:18:05 25 4
gpt4 key购买 nike

我想创建一个字典列表,每个列表中具有相同的索引元素。

我有这本字典:

d = {'name': ['bob', 'john', 'harry', 'mary'], 
'age': [13, 19, 23],
'height': [164, 188],
'job': ['programmer']}

所需的输出是:

d2 = [{'name': 'bob', 'age': 13, 'height': 164, 'job': 'programmer'}, 
{'name': 'john', 'age': 19, 'height': 188},
{'name': 'harry', 'age': 23},
{'name': 'mary'}]

我尝试过这样的事情:

d2 = [dict(zip(d, t)) for t in zip(*d.values())]

但我的输出是:

d2 = [{'name': 'bob', 'age': 13, 'height': 164, 'job': 'programmer'}]

我认为发生这种情况是因为列表的长度不同。

最佳答案

您可以使用itertools.zip_longest并过滤掉 None 值:

from itertools import zip_longest

[{x: y for x, y in zip(d, t) if y is not None} for t in zip_longest(*d.values())]
# [{'name': 'bob', 'age': 13, 'height': 164, 'job': 'programmer'},
# {'name': 'john', 'age': 19, 'height': 188},
# {'name': 'harry', 'age': 23},
# {'name': 'mary'}]

关于python - 如何从具有不同长度列表的字典创建字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57850869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com