The Python Oracle

Python: Change values in a dict based on list?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle3

--

Chapters
00:00 Python: Change Values In A Dict Based On List?
00:28 Answer 1 Score 3
00:47 Accepted Answer Score 7
01:08 Thank you

--

Full question
https://stackoverflow.com/questions/6291...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 7


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}



ANSWER 2

Score 3


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)