【问题标题】:Updating a list of python dictionaries with a key, value pair from another list使用另一个列表中的键、值对更新 python 字典列表
【发布时间】:2012-05-15 00:15:58
【问题描述】:

假设我有以下 python 字典列表:

dict1 = [{'domain':'Ratios'},{'domain':'Geometry'}]

还有一个类似的列表:

list1 = [3, 6]

我想更新dict1 或创建另一个列表,如下所示:

dict1 = [{'domain':'Ratios', 'count':3}, {'domain':'Geometry', 'count':6}]

我该怎么做?

【问题讨论】:

  • 根据示例,这个问题的标题应该是:“从另一个列表更新python字典值的列表”。从当前标题中,我希望 list1 = [('Ratios', 3), ('Geometry', 6)]

标签: python list dictionary


【解决方案1】:
>>> l1 = [{'domain':'Ratios'},{'domain':'Geometry'}]
>>> l2 = [3, 6]
>>> for d,num in zip(l1,l2):
        d['count'] = num


>>> l1
[{'count': 3, 'domain': 'Ratios'}, {'count': 6, 'domain': 'Geometry'}]

另一种方法,这次使用不会改变原始列表的列表理解:

>>> [dict(d, count=n) for d, n in zip(l1, l2)]
[{'count': 3, 'domain': 'Ratios'}, {'count': 6, 'domain': 'Geometry'}]

【讨论】:

  • 谢谢。第二种解决方案在其当前形式中产生错误
  • 你用的是python 3吗?我可能会将其更改为交叉兼容。
  • 哪个计算速度更快?
  • @amc 这可能不值得担心:P 但可以在上面运行一些timeits
【解决方案2】:

你可以这样做:

for i, d in enumerate(dict1):
    d['count'] = list1[i]

【讨论】:

    【解决方案3】:

    你可以这样做:

    # list index
    l_index=0
    
    # iterate over all dictionary objects in dict1 list
    for d in dict1:
    
        # add a field "count" to each dictionary object with
        # the appropriate value from the list
        d["count"]=list1[l_index]
    
        # increase list index by one
        l_index+=1
    

    此解决方案不会创建新列表。相反,它会更新现有的dict1 列表。

    【讨论】:

    • 对 Python 来说非常冗长,但对所有内容的解释都非常好。
    • 是的,你说得对!它非常冗长。但由于这里还有其他不那么冗长的答案,我认为可以添加一个更具解释性的解决方案..
    • 感谢您的详细解释。
    【解决方案4】:

    使用列表推导将是 Python 的方式。

    [data.update({'count': list1[index]}) for index, data in enumerate(dict1)]
    

    dict1 将使用来自list1 的相应值进行更新。

    【讨论】:

    • -1 对突变使用列表理解是不是 pythonic。使用简单的 for 循环。
    • 在参考文献上更新字典工作不提供输出。 data.update() 返回无。你会得到 [None, None, ....]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 2021-05-31
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多