0

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:

{"aaa": [], 'bbb':[]}

1
  • 7
    {i: [] for i in my_list} Commented Aug 29, 2019 at 9:54

3 Answers 3

4
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})

output:

{'aaa': [], 'bbb': []}
Sign up to request clarification or add additional context in comments.

Comments

1

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})

Comments

0

I think so:

my_dict = dict()
my_list = ["aaa", "bbb"]
for el in my_list:
    my_dict[el] = []

print(my_dict) 

Comments

Your Answer

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.

Ask question

Explore related questions

See similar questions with these tags.