【问题标题】:Parse list into dictionaries within a dictionary Python将列表解析为字典 Python 中的字典
【发布时间】:2018-02-11 07:58:15
【问题描述】:

数据集:

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

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

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 循环,它无法正常工作。内部字典的值只是替换自己,直到最后一个子列表。

如何更正此代码?

【问题讨论】:

    标签: python python-2.7 dictionary nested


    【解决方案1】:

    你可以试试这个:

    id = [1,2,3]
    header = ['name','attack','defense']
    stats = [['John',12,30], ['Amy',32,89], ['Lisa',45,21]]
    
    new_dict = {a:{d:c for c, d in zip(b, header)} for a, b 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'}}
    

    【讨论】:

      【解决方案2】:

      您不需要遍历统计信息子列表;使用您选择的 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() function 将两个列表配对以进行并行迭代:

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

      这使用dictionary comprehension 构建从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'}}
      

      【讨论】:

      • _ 是否仅表示 IDLE/REPL 中的最后一个输出?
      • @NickA:是的,Python REPL 会跟踪该变量中不是 None 的最后一个表达式语句结果。
      • @MartijnPieters 我假设 dict(zip(header, stats)) 会给我一个输出 {name: [John, 12, 30], attack:[Amy, 32,89],防守:[Lisa,45,21]}?
      • @MartijnPieters 顺便说一句,我无法运行该代码。我面临一个 TypeError: 'dict' object is not callable。我该如何解决这个问题?抱歉,我已经解决了这个问题。
      • @TimOng:我用的是stat,而不是stats;不同的变量。 stat 首先绑定到['John', 12, 30],所以zip(header, stat) 给你[('name', 'John'), ('attack', 12), ('defense', 30)],它被传递给dict()。您在代码中使用了dict 作为变量,因此您屏蔽了内置类型。使用del dict 删除该名称,然后重试。
      【解决方案3】:

      另一个zip() 变体:

      d = {}
      for i,s in enumerate(stats):
          d[id[i]] = dict((zip(header, s)))
      
      print(d)
      

      输出:

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

      【讨论】:

        【解决方案4】:

        使用 zip()list comphersion

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

        首先使用标题压缩统计信息中的每个项目

        >>> [dict(zip(header,item)) for item in stats]
        
        [{'attack': 12, 'defense': 30, 'name': 'John'}, {'attack': 32, 'defense': 89, 'name': 'Amy'}, {'attack': 45, 'defense': 21, 'name': 'Lisa'}]
        

        带有第一个输出的第二个 zip id

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-30
          • 2021-11-04
          • 1970-01-01
          相关资源
          最近更新 更多