【问题标题】:How do you join a list to a dictionary of lists as a new item - python?如何将列表作为新项目加入列表字典 - python?
【发布时间】:2019-06-07 22:41:55
【问题描述】:

也许是一个简单的问题:

在 python 中,我有一个字典列表,我想在列表中的每个字典中添加一个列表作为新项目?

例如我有字典列表:

list_dict =[{'id':1, 'text':'John'},
            {'id':2, 'text':'Amy'},
            {'id':3, 'text':'Ron'}]

还有一个清单:

list_age = [23, 54, 41]

然后我如何添加列表以生成字典列表:

list_dict =[{'id':1, 'text':'John', 'age':23},
            {'id':2, 'text':'Amy', 'age':54},
            {'id':3, 'text':'Ron', 'age':41}]

我不确定此处使用的正确代码?

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    使用zip,遍历匹配对并更新字典:

    >>> for d, a in zip(list_dict, list_age):
    ...     d["age"] = a
    ... 
    >>> list_dict
    [{'id': 1, 'text': 'John', 'age': 23}, {'id': 2, 'text': 'Amy', 'age': 54}, {'id': 3, 'text': 'Ron', 'age': 41}]
    

    【讨论】:

      【解决方案2】:

      这样的东西可以工作

      for index, item in enumerate(list_age):
        list_dict[index]['age'] = item
      

      编辑: 正如@Netwave 提到的,您应该确保len(list_age) 不大于len(list_dict)

      【讨论】:

      • 是的!为什么其他人都在使用 zip(),我不明白,因为这是更直观的方式
      • 是的,我也发现 enumerate 是一个更简单的解决方案。
      • 是的,这是一个很好的解决方案。请注意,您正在修改 list_dict,因此应该从那里获取大小。在使用 zip 时,如果迭代该列表已用尽,它将停止,在此解决方案中,如果 list_age 只是一个更大的项目,则可能会出现索引错误。
      【解决方案3】:

      如果list_agelist_dict 的长度相同,请尝试此循环:

      for i, j in zip(list_dict, list_age):
        i['age']=j
      

      输出

      [{'id': 1, 'text': 'John', 'age': 23}, {'id': 2, 'text': 'Amy', 'age': 54}, {'id': 3, 'text': 'Ron', 'age': 41}]
      

      【讨论】:

        【解决方案4】:

        添加列表以生成字典列表:

        for a, b in zip(list_dict, list_englishmark):
            a["englishmark"] = b
        
        print(list_dict)
        

        输出:

        [{'id': 1, 'name': 'mari', 'englishmark': 80}, {'id': 2, 'name': 'Arun', 'englishmark': 54}, {' id': 3, 'name': 'ram', 'englishmark':75}]

        【讨论】:

        • 这看起来与一个月前发布的其他三个答案基本相同。我看不出这增加了什么
        • @jdd 我的意思是这个问题的其他答案。可能不是公认的答案,但肯定是其他两个答案。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-23
        • 2012-07-12
        • 1970-01-01
        • 1970-01-01
        • 2021-07-02
        相关资源
        最近更新 更多