How can I add keys to a dict within a list, if the dict contains a certain key, from values in another list?
I have a list of dicts. Those dicts either contain only one key ('review'), or two keys ('review' and 'response'). When the dict contains the key 'response', I want to add two keys, with values from two lists.
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']
I have tried the following, but since for each dict that contains the key 'response' I only want to add 1 from the values from each lists, I am not sure how to do this.
for d in data:
if 'response' in d:
for i in date:
d['date'] = i
for i in responder:
d['responder'] = i
The output shows me that it of course only adds the last values of the lists since I'm looping over the lists. How can I fix this?
[{'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'}]
You can create an iterator for your date and responder lists and then call next()
in your if statement to take the next item from the list
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'}
]
You can try this, but be careful, because of number of response
on your list should be equals to length your lists:
d_r = zip(date, responder)
for d in data:
if 'response' in d:
d['date'], d['responder'] = next(d_r)
print(data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With