my_dict = {'a':'1', 'b':2, 'c':3}
my_list = ['a','b','d']
for element in my_list:
if element not in my_dict:
my_dict[element] =1
Can this for loop be replaced by a one-line code in Python? I can’t use dict or list comprehension to do it.
>Solution :
You can pass a dict into update():
my_dict = {'a':'1', 'b':2, 'c':3}
my_list = ['a','b','d']
my_dict.update({k:1 for k in my_list if k not in my_dict })
my_dict
# {'a': '1', 'b': 2, 'c': 3, 'd': 1}