1

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.

Lafexlos
  • 7,618
  • 5
  • 38
  • 53
vikrant Verma
  • 478
  • 3
  • 8
  • 17
  • refer this - http://stackoverflow.com/questions/4576115/convert-a-list-to-a-dictionary-in-python – Vinay Dec 27 '16 at 06:59

2 Answers2

6
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).

disatisfieddinosaur
  • 1,502
  • 10
  • 15
3

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'}]
vishes_shell
  • 22,409
  • 6
  • 71
  • 81