5

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?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Mahamutha M
  • 1,235
  • 1
  • 8
  • 24
  • 1
    This is not a problem you should solve with a list or dict comprehension. Just write a regular ol' loop. – Aran-Fey Apr 11 '19 at 07:18

3 Answers3

5

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'}]
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
1
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'}]
Travis
  • 109
  • 5
1

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'}]
cph_sto
  • 7,189
  • 12
  • 42
  • 78
  • Don't use list comprehensions with side effects: [Is it Pythonic to use list comprehensions for just side effects?](https://stackoverflow.com/questions/5753597/is-it-pythonic-to-use-list-comprehensions-for-just-side-effects) – Georgy Apr 11 '19 at 09:19
  • @Georgy Thanks for bringing it to my notice. – cph_sto Apr 11 '19 at 09:20