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':[]}
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': []}
如果my_dict已经存在,并且您要添加更多项目,则可以使用以下代码
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.