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(ie, "mac") and value(ie, "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?
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'}]
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'}]
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'}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.