我有两本字典。当list_dicts2
文本中出现相应的名称时,我想附加到list_dicts1
的嵌套字典中。例如,在list_dicts2
中,名称“Nat”出现在两个不同的文本中,因此我想将其附加到list_dicts1
中包含“Nat”的嵌套字典中
问题:当名称出现在多个文本中时,我的代码会创建一个新的字典条目,而不是将其附加到同一个字典中
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循环之外,应该会得到正确的输出查看键
'name'
的值是否在键'text'
的值中,如果是这种情况,请将整个字典添加到键'nested'
这条线
返回键
'nested'
的字典内部列表,因为该值最初是一个包含一个字典的列表,而且b_dict
只是一个字典相关问题 更多 >
编程相关推荐