37

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
  • 2,954
  • 7
  • 34
  • 49
  • 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

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

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

Fred Foo
  • 342,876
  • 71
  • 713
  • 819
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
  • 5,955
  • 5
  • 32
  • 46