Question: Making dictionary from two lists


Making dictionary from two lists

Answers 2
Added at 2016-12-27 07:12

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.

nr: #1 dodano: 2016-12-27 08:12
result = [{'name': name, 'id': id} for (name, id) in zip(l1, l2)]

It doesn't make sense for the container all the individual dicts are in to be a dict as well (unless you want to key it on, say, id).

nr: #2 dodano: 2016-12-27 08:12

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


[{'id': 1, 'name': 'cat'}, {'id': 2, 'name': 'dog'}]
Source Show
◀ Wstecz