[英]Python: Change values in a dict based on list?
I have a dict check_dict
with keys and values.我有一个带有键和值的字典check_dict
。 And another list input_list
with keys
.另一个带有keys
的列表input_list
。
I'm trying to make keys in check_dict
to true whose keys are present in input_list
.我正在尝试将check_dict
中的键设置为 true ,其键存在于input_list
中。
input_list = ['name', 'phone']
check_dict = {'name':False,'phone':False,'address':False}
Expected output:预期 output:
final_dict = {'name':True,'phone':True,'address':False}
If you want to use dict-comprehension:如果你想使用 dict-comprehension:
>>> input_list = ['name', 'phone']
>>> check_dict = {'name':False,'phone':False,'address':False}
>>> final_dict = {k: True if k in input_list else False for k in check_dict}
>>> final_dict
{'name': True, 'phone': True, 'address': False}
As @ScootCork mentioned in a comment, this will do the same, but is much more readable:正如@ScootCork 在评论中提到的那样,这将做同样的事情,但更具可读性:
final_dict = {k: k in input_list for k in check_dict}
You can iterate over input_list
and then make an if
statement.您可以遍历input_list
然后进行if
语句。 If a string
from the input_list
is in the check_dict
then we change it's value to True
如果input_list
中的string
在check_dict
中,那么我们将其值更改为True
input_list = ['name', 'phone']
check_dict = {'name':False,'phone':False,'address':False}
for i in input_list:
if i in check_dict:
check_dict[i] = True
print(check_dict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.