本文介绍了用另一个列表中的键,值对更新python字典的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下python字典列表: dict1 = [{'domain':'比率'} ,{'domain':'Geometry'}]
和一个列表,如:
list1 = [3,6]
我想更新 dict1
或创建另一个列表,如下所示:
dict1 = [{'domain':'比率','count':3},{'domain':'几何','count':6}]
我该怎么做?
解决方案
>>> l1 = [{'domain':'Ratios'},{'domain':'Geometry'}]
/ pre>
>>> l2 = [3,6]
>>>对于d,zip中的num(l1,l2):
d ['count'] = num
>>> l1
[{'count':3,'domain':'Ratios'},{'count':6,'domain':'Geometry'}]
另一种做法,这次用列表理解不会使原来的变体:
>>> d(n,d,n,n)在zip(l1,l2)]
[{'count':3,'domain':'比率'},{'count'域':'几何'}]
Let's say I have the following list of python dictionary:
dict1 = [{'domain':'Ratios'},{'domain':'Geometry'}]
and a list like:
list1 = [3, 6]
I'd like to update
dict1
or create another list as follows:dict1 = [{'domain':'Ratios', 'count':3}, {'domain':'Geometry', 'count':6}]
How would I do this?
解决方案>>> 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'}]
Another way of doing it, this time with a list comprehension which does not mutate the original:
>>> [dict(d, count=n) for d, n in zip(l1, l2)] [{'count': 3, 'domain': 'Ratios'}, {'count': 6, 'domain': 'Geometry'}]
这篇关于用另一个列表中的键,值对更新python字典的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!