【问题标题】:How to add a list of values to a list of nested dictionaries?如何将值列表添加到嵌套字典列表中?
【发布时间】:2021-01-26 14:46:52
【问题描述】:

我想将列表的每个值添加到不同列表的每个嵌套字典中,并使用新的键名。

词典列表:

list_dicts = [{'id': 1, 'text': 'abc'}, {'id':2, 'text': 'def'}]

列表:

list = ['en', 'nl']

期望的输出:

list_dicts = [{'id': 1, 'text': 'abc', 'language': 'en'}, {{'id':2, 'text': 'def', 'language':'nl'}]

当前使用的方法: 我将list_dicts 转换为Pandas 数据框,添加了代表list 值的新列“语言”。然后,我使用df.to_dict('records') 将 Pandas 数据框转换回字典列表。必须有一种更有效的方法来遍历列表并将每个值添加到字典列表中的新分配键中,而根本不需要使用 Pandas。有什么想法吗?

【问题讨论】:

    标签: python list loops dictionary nested


    【解决方案1】:
    list = ['en', 'nl']   # Don't use list as variable name tho.
    list_dicts = [{'id': 1, 'text': 'abc'}, {'id':2, 'text': 'def'}]
    
    
    for i,item in enumerate(list):
        list_dicts[i]['language'] = item
    

    如果您只想为“语​​言”键分配值,那应该可以解决问题。

    【讨论】:

      【解决方案2】:

      使用zip 的列表推导

      例如:

      list_dicts = [{'id': 1, 'text': 'abc'}, {'id':2, 'text': 'def'}]
      lst = ['en', 'nl']
      
      list_dicts = [{**n, "language": m} for n,m in zip(list_dicts, lst)]
      print(list_dicts)
      # --> [{'id': 1, 'text': 'abc', 'language': 'en'}, {'id': 2, 'text': 'def', 'language': 'nl'}]
      

      【讨论】:

      • 这会在为理解而重建字典时添加不必要的迭代。
      【解决方案3】:

      对压缩列表进行简单的循环即可:

      for d, lang in zip(list_dicts, list):
          d["language"] = lang
      

      旁注:您不应该将变量命名为 list,而不是隐藏内置名称。

      【讨论】:

        【解决方案4】:

        试试这样(不要使用list作为变量名):

        list_dicts = [{'id': 1, 'text': 'abc'}, {'id':2, 'text': 'def'}]
        langlist = ['en', 'nl']
        x = 0
        for y in list_dicts:
          y['language'] = langlist[x]
          x=x+1
        
        print(list_dicts)
        

        【讨论】:

          【解决方案5】:

          简单地说:

          for d, l in zip(list_dicts, list):
              d['language'] = l
          

          然后:

          print(list_dicts)
          

          【讨论】:

            【解决方案6】:

            (假设两个列表的长度相同)

            list_dicts = [{'id': 1, 'text': 'abc'}, {'id':2, 'text': 'def'}]
            
            list_lang = ['en', 'nl'] 
            
            for i in range(len(list_dicts)):
                list_dicts[i]['language']=list_lang[i]
            
            >>> print(list_dicts)
            [{'id': 1, 'text': 'abc', 'language': 'en'}, {'id': 2, 'text': 'def', 'language': 'nl'}]
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2017-06-17
              • 2018-06-20
              • 1970-01-01
              • 1970-01-01
              • 2021-05-10
              • 2021-01-23
              • 2020-09-15
              相关资源
              最近更新 更多