I have two lists
l1 = ['cat','dog']
l2= [1,2]
Now I want to make a dictionary like this:
dict { {'name':cat,'id'=1}{'name':dog,'id'=2}}
I am using zip
but that's not fulfilling my requirement.
result = [{'name': name, 'id': id} for (name, id) in zip(l1, l2)]
将容器中的所有单个字典也都当作字典是没有意义的(除非您想将其键入id)。
If you have a lot of keys and you don't want to create dict comprehension and declare what goes where.
l1 = ['cat','dog']
l2= [1,2]
[dict(zip(['name', 'id'], el)) for el in zip(l1,l2)]
Output:
[{'id': 1, 'name': 'cat'}, {'id': 2, 'name': 'dog'}]
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.