Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding keys to dicts within a list, from values in a list

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'}]
like image 428
Lisadk Avatar asked Oct 16 '17 11:10

Lisadk


2 Answers

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'}
]
like image 146
AK47 Avatar answered Nov 10 '22 00:11

AK47


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)
like image 45
amarynets Avatar answered Nov 10 '22 02:11

amarynets