将列表解析为字典 Python 中的字典

心王

数据集:

id = [1,2,3]
header = ['name','attack','defense']
stats = [['John',12,30], ['Amy',32,89], ['Lisa',45,21]]

我想以嵌套字典的形式获得输出。外部字典的键将是 id,值将是包含其他数据的字典。IE:

dict = {
    1: {'name': 'John', 'attack': 12, 'defense': 30}, 
    2: {'name': 'Amy', 'attack': 32, 'defense': 89},
    3: {'name': 'Lisa', 'attack': 45, 'defense': 21}
}

这是我当前的代码:

dict = {}
for i in id:
    next_input = {}
    for index, h in enumerate (header):
        for sublist in stats:
            next_input[h] = sublist[index]
    dict[i] = next_input

由于最后一个 for 循环,它不起作用。内部字典的值只是替换自己,直到最后一个子列表。

如何更正此代码?

马丁·彼得斯

您不需要遍历 stats 子列表;使用enumerate()您选择选项,您必须向id循环添加索引并选择正确的统计信息:

dict = {}
for id_index, i in enumerate(id):
    next_input = {}
    for h in enumerate (header):
        next_input[h] = sublist[id_index][index]
    dict[i] = next_input

但是,您可以使用该zip()函数将两个列表配对以进行并行迭代:

result = {i: dict(zip(header, stat)) for i, stat in zip(id, stats)}

这使用字典理解来构建从id值到相应stats条目的外部映射内部字典只是从配对的标题和统计信息(dict()采用一系列(key, value)对)构建而成

演示:

>>> id = [1,2,3]
>>> header = ['name','attack','defense']
>>> stats = [['John',12,30], ['Amy',32,89], ['Lisa',45,21]]
>>> {i: dict(zip(header, stat)) for i, stat in zip(id, stats)}
{1: {'attack': 12, 'defense': 30, 'name': 'John'}, 2: {'attack': 32, 'defense': 89, 'name': 'Amy'}, 3: {'attack': 45, 'defense': 21, 'name': 'Lisa'}}
>>> from pprint import pprint
>>> pprint(_)
{1: {'attack': 12, 'defense': 30, 'name': 'John'},
 2: {'attack': 32, 'defense': 89, 'name': 'Amy'},
 3: {'attack': 45, 'defense': 21, 'name': 'Lisa'}}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章