[英]How to add a key and value using list and dict comprehension in list of dictionaries?
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, 现在我需要在字典中添加一个新键(即“mac”)和值(即“xyz”),如果字典包含'data'= 1并且结果应该是,
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? 任何人都可以帮助我在单个表达式中同时使用list和dict理解来实现“expected_outcome”吗?
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. 是因为您要向列表中的每个元素添加
{'mac':'xyz'}
。
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,如果ip_list元素的键中存在
data
则添加{'mac':'xyz'}
, data
值为'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
. 使用
list comprehensions
在if-else
的帮助下解决这个问题。 You can add elements to the dictionary using update()
function - 您可以使用
update()
函数向字典添加元素 -
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'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.