Python: Change values in a dict based on list?

Viewed 104

I have a dict check_dict with keys and values. And another list input_list with keys.

I'm trying to make keys in check_dict to true whose keys are present in input_list.

input_list = ['name', 'phone']

check_dict = {'name':False,'phone':False,'address':False}

Expected output:

final_dict = {'name':True,'phone':True,'address':False}
2 Answers

If you want to use 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:

final_dict = {k: k in input_list for k in check_dict}

You can iterate over input_list and then make an if statement. If a string from the input_list is in the check_dict then we change it's value to 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)
Related