39

I have read this link

But how do I initialize the dictionary as well ?

say two list

 keys = ['a','b','c','d'] 
 values = [1,2,3,4] 
 dict = {}

I want initialize dict with keys & values

Community
  • 1
  • 1
Jibin
  • 3,054
  • 7
  • 36
  • 51
  • 3
    If you had actually read the *question*, you'd have seen that the code shown there solves your problem. – Björn Pollex Nov 10 '11 at 14:21
  • How do i give `b` as a list in `dict.fromkeys(a,b)` – Jibin Nov 11 '11 at 09:58
  • You don't, but at the end of the question the OP shows the code `dict(zip(keys, [None]*len(keys)))`, which is essentially the same as the accepted answer on your question here (`[None]*len(keys)` builds a list that contains `len(keys)` times `None` ). – Björn Pollex Nov 11 '11 at 10:14

2 Answers2

96
d = dict(zip(keys, values))

(Please don't call your dict dict, that's a built-in name.)

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
20

In Python 2.7 and python 3, you can also make a dictionary comprehension

d = {key:value for key, value in zip(keys, values)}

Although a little verbose, I found it more clear, as you clearly see the relationship.

Khelben
  • 6,283
  • 6
  • 33
  • 46