【发布时间】:2021-03-12 15:56:24
【问题描述】:
我有两个字典列表。我想追加到list_dicts1的嵌套字典中,当list_dicts2的文本中出现对应的名称时。例如。在list_dicts2 中,名称“Nat”出现在两个不同的文本中,所以我想将其附加到包含“Nat”的嵌套字典中 list_dicts1
问题:当名称出现在多个文本中时,我的代码会创建一个新的字典条目,而不是将其附加到同一个字典中。
list_dicts1= [{'id': '1', 'name': 'John', 'nested':[{'id': '1', 'text': 'text1'}]},
{'id': '2', 'name': 'Nat', 'nested':[{'id': '2', 'text': 'text2'}]}]
list_dicts2=[{'id': 'A', 'text': 'this text contains the name John'},
{'id': 'B', 'text': 'this text contains the name Nat'},
{'id': 'C', 'text': 'this text also contains the name Nat'}]
期望的输出:
[{'id': '1',
'name': 'John',
'nested': [{'id': '1', 'text': 'text1'},
{'id': 'A', 'text': 'this text contains the name John'}]},
{'id': '2',
'name': 'Nat',
'nested': [{'id': '2', 'text': 'text2'},
{'id': 'B', 'text': 'this text contains the name Nat'},
{'id': 'C', 'text': 'this text also contains the name Nat'}]}]
我的代码:
for d in list_dicts1:
for dic in list_dicts2:
if d.get('name', '') in dic.get('text', ''):
d["nested"].append(dic)
print(d)
当前输出:
[{'id': '1',
'name': 'John',
'nested': [{'id': '1', 'text': 'text1'},
{'id': 'A', 'text': 'this text contains the name John'}]},
{'id': '2',
'name': 'Nat',
'nested': [{'id': '2', 'text': 'text2'},
{'id': 'B', 'text': 'this text contains the name Nat'}]},
{'id': '2',
'name': 'Nat',
'nested': [{'id': '2', 'text': 'text2'},
{'id': 'B', 'text': 'this text contains the name Nat'},
{'id': 'C', 'text': 'this text also contains the name Nat'}]}]
正如您所见,在当前输出中创建了一个新的“Nat”条目,这不是我们的想法。
我希望我的问题足够清楚(通过将这些词典粘贴到您的编辑器中最容易重现)。在发布问题之前,我在代码中重现了这个问题。
【问题讨论】:
-
当我尝试运行你的代码时,我得到了正确的输出。
-
是
print语句的当前“输出”吗? -
打印语句在每次迭代中执行。你不应该在最后打印一次吗?
-
将打印语句移到“
for d in list_dicts1”块之外 -
所以你的答案给出了这个问题的正确输出 - 但不幸的是它不是我要找的,因为“list_dicts1”实际上是一个 solr 数据库对象(在我的代码中),但我试图在这里重现它带有虚拟数据。我要解决的问题最后没有写在我自己的问题中,但是很难在 stackoverflow 上重现 - 但我会接受你的回答,谢谢。
标签: python list dictionary for-loop nested