如果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'}]
答案 0 :(得分:4)
您可以为日期和响应者列表创建一个迭代器,然后在if语句中调用next()
以从列表中获取下一个项目
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']
d_iter = iter(date)
r_iter = iter(responder)
for d in data:
if 'response' in d:
d['date'] = next(d_iter)
d['responder'] = next(r_iter)
print(data)
>> [
{'date': '4 days ago',
'review': 'This is a review',
'responder': 'Manager',
'response': 'This is a response'},
{'review': 'This is only a review'},
{'date': '3 days ago',
'review': 'This is also a review',
'responder': 'Customer service',
'response': 'This is also a response'}
]
答案 1 :(得分:2)
你可以试试这个,但要小心,因为你名单上response
的数量应该等于列表的长度:
d_r = zip(date, responder)
for d in data:
if 'response' in d:
d['date'], d['responder'] = next(d_r)
print(data)
答案 2 :(得分:0)
我认为您正在尝试添加两个条目,其中Date为键,值不同。在字典中你不能有重复的键。这就是为什么在for循环字典只更新了一个日期键条目和只有一个响应者条目
之后