python - 使用另一个列表中的键值对更新 python 字典列表

标签 python list dictionary

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

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

和一个像这样的列表:

list1 = [3, 6]

我想按如下方式更新 dict1 或创建另一个列表:

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

我该怎么做?

最佳答案

>>> 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 - 使用另一个列表中的键值对更新 python 字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10592674/

相关文章:

python - 从 python "Error: This command requires a Cask token"使用 Homebrew

python - 如何在 Python 上生成 DOT 语言输出

list - SharePoint 2010中如何获取列表的odata服务

python - 从不同线程修改 Python 字典

python - 如何使用两个相同的键和不同的值从 Python 中的三个不同列表创建字典?

python - tf.print() vs Python print vs tensor.eval()

python >=3.5 : Checking type annotation at runtime

python - 在python中的类中定义一个方法

R - 从 data.frames 列表中提取信息

python - 如何在函数中使用 *args 返回字典列表?