[英]Dictionaries in list: conditional update with .update()
I am trying to update dictionaries in a list nodes
with tuples in another list source
with a conditional. 我正在尝试使用条件列表在另一个列表
source
元组中更新列表nodes
字典。
Tuple list: 元组列表:
source = [('144 IV 285', 16),
('144 IV 1', 11),
('141 IV 155', 7)]
Dictionary list: 字典清单:
nodes = [{'id': '144 IV 285','date': '2018-08-15','relevancy': 10, 'outDegree': 18},
{'id': '144 IV 240','date': '2016-08-15','relevancy': 4, 'outDegree': 10}]
Each item in 'nodes' should be extended by a new key ( inDegree
) value pair based on the 'source' list. “节点”中的每个项目都应基于“源”列表扩展一个新的键(
inDegree
)值对。 My code: 我的代码:
for item in sources:
for item2 in nodes:
if item2["id"] == item[0]:
item2.update( {"inDegree": item[1]})
else:
item2.update( {"inDegree": 0})
Problem: How can I populate the key inDegree
either by the value in the source list or 0, if there is no matching id for an item in 'nodes' in the 'source' list? 问题:如果“源”列表中“节点”中的项目没有匹配的ID,如何用源列表中的值或0填充
inDegree
键?
Problem is that it is iterating source
even after there was a match, and thus overwrite the previous update. 问题在于,即使存在匹配项,它也正在迭代
source
,因此将覆盖以前的更新。 You can unpack your source
and do comparison: 您可以解压缩
source
并进行比较:
for item2 in nodes:
sources = list(zip(*source))
if item2["id"] in sources[0]:
item2.update({"inDegree": sources[1][sources[0].index(item2["id"])]})
else:
item2.update({"inDegree": 0})
print(nodes)
[{'id': '144 IV 285',
'date': '2018-08-15',
'relevancy': 10,
'outDegree': 18,
'inDegree': 16},
{'id': '144 IV 240',
'date': '2016-08-15',
'relevancy': 4,
'outDegree': 10,
'inDegree': 0}]
Try this: 尝试这个:
for item in nodes:
for item2 in source:
if item["id"] == item2[0]:
item.update( {"inDegree": item2[1]})
break
else:
item.update( {"inDegree": 0})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.