4
votes

I have a list of dictionaries which is,

ip_list = [{'1403': [-56, -58], 'data': '1'},
           {'1403': [-56, -58], 'data': '0'}]

Now I need to add a new key(i.e., "mac") and value(i.e., "xyz") in a dictionary if dictionary contains 'data' = 1 and the outcome should be,

expected_outcome = [{'1403': [-56, -58], 'data': '1', 'mac':'xyz'},
                    {'1403': [-56, -58], 'data': '0'}]

I have tried with the,

list_dict_comp = [dict(item, **{'mac':'xyz'}) for item in ip_list]

Whereas, the above expression gives,

list_dict_comp = [{'1403': [-56, -58], 'data': '1', 'mac':'xyz'},
                  {'1403': [-56, -58], 'data': '0', 'mac':'xyz'}]

Can anyone help me out to achieve the "expected_outcome" using both list and dict comprehension together in a single expression?

3
This is not a problem you should solve with a list or dict comprehension. Just write a regular ol' loop. - Aran-Fey

3 Answers

4
votes

The reason you get

list_dict_comp = [{'1403': [-56, -58], 'data': '1', 'mac':'xyz'},
                  {'1403': [-56, -58], 'data': '0', 'mac':'xyz'}]

is because you are adding {'mac':'xyz'} to every element in the list.

Why not make your life easier and just iterate through ip_list, and add {'mac':'xyz'} if data is present in the keys of an element of ip_list, and the value for data is '1'

ip_list = [{'1403': [-56, -58], 'data': '1'},
           {'1403': [-56, -58], 'data': '0'}]

for ip in ip_list:
    if ip.get('data') == '1':
        ip['mac'] = 'xyz'
print(ip_list)
#[{'1403': [-56, -58], 'data': '1', 'mac': 'xyz'}, {'1403': [-56, -58], 'data': '0'}]
1
votes
ip_list = [{'1403': [-56, -58], 'data': '1'},
           {'1403': [-56, -58], 'data': '0'}]
res = [dict(item, **{'mac':'xyz'}) if 'data' in item and item['data'] == '1' else item for item in ip_list]
print(res)
# [{'1403': [-56, -58], 'data': '1', 'mac': 'xyz'}, {'1403': [-56, -58], 'data': '0'}]
1
votes

Use list comprehensions to solve this with the help of if-else. You can add elements to the dictionary using update() function -

ip_list = [{'1403': [-56, -58], 'data': '1'}, {'1403': [-56, -58], 'data': '0'}]

[i.update({'mac': 'xyz'}) if i['data']=='1' else i for i in ip_list]         

print(ip_list)
     [{'1403': [-56, -58], 'data': '1', 'mac': 'xyz'},
      {'1403': [-56, -58], 'data': '0'}]