如果dict包含某个键,如何从列表中的值中添加键到列表中的dict?
我有一个dicts列表.这些dicts只包含一个键(‘review’)或两个键(‘review’和’response’).当dict包含键’response’时,我想添加两个键,其中包含两个列表中的值.
data = [{'response': 'This is a response',
'review': 'This is a review'},
{'review': 'This is only a review'},
{'response': 'This is also a response',
'review': 'This is also a review'}]
date = ['4 days ago',
'3 days ago']
responder = ['Manager',
'Customer service']
我尝试了以下内容,但由于每个包含密钥“响应”的dict我只想从每个列表的值中添加1,我不知道如何做到这一点.
for d in data:
if 'response' in d:
for i in date:
d['date'] = i
for i in responder:
d['responder'] = i
输出显示我当然只添加列表的最后一个值,因为我循环遍历列表.我怎样才能解决这个问题?
[{'date': '3 days ago',
'responder': 'Customer service',
'response': 'This is a response',
'review': 'This is a review'},
{'review': 'This is only a review'},
{'date': '3 days ago',
'responder': 'Customer service',
'response': 'This is also a response',
'review': 'This is also a review'}]