如果dict包含某个键,如何从另一个列表中的值向列表中的dict添加键?你知道吗
我有一张单子。这些dict要么只包含一个键(“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']
我尝试了以下方法,但是因为对于每个包含键“response”的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'}]
您可以为日期和响应者列表创建迭代器,然后在if语句中调用
next()
,从列表中获取下一项您可以尝试这样做,但要小心,因为列表上的
response
数应该等于列表的长度:我认为您正在尝试添加两个以日期为键的条目,并且值不同。在字典里你不能有重复的键。这就是为什么在for循环字典只更新了一个日期键条目和一个响应者条目之后
相关问题 更多 >
编程相关推荐