Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
How to create list from loop?
I have got list:
my_dict = dict() my_list = ["aaa", "bbb"] for el im my_list: #
I want to add to my_dict element with name from loop, to get in my_dict:
my_dict
{"aaa": [], 'bbb':[]}
{i: [] for i in my_list}
my_dict = dict() my_list = ["aaa", "bbb"] for el in my_list: my_dict[el] = [] print (my_dict)
output:
{'aaa': [], 'bbb': []}
or use list comprehension:
my_dict = dict() my_list = ["aaa", "bbb"] print ({el:[] for el in my_list})
Add a comment
If my_dict is already existing dict and you want to add more items to that then you can use the below code
my_dict.update({key:[] for key in my_list})
I think so:
my_dict = dict() my_list = ["aaa", "bbb"] for el in my_list: my_dict[el] = [] print(my_dict)
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.
{i: [] for i in my_list}