4

I've gone through many questions but couldn't find what i was looking for. I have a list something like this: [2, 3, 5, 7, 11]
and I want to convert it into a dictionary in the format: i.e. the values of the list should be keys and each associated value should be zero. {2:0 , 3:0 , 5:0 , 7:0 , 11:0}

codenamered5
  • 63
  • 1
  • 1
  • 10

2 Answers2

18

A dict comprehension will do.

my_list = [2, 3, 5, 7, 11]
my_dict = {k: 0 for k in my_list}  # {2:0 , 3:0 , 5:0 , 7:0 , 11:0}

Even if you are not familiar at all with comprehensions you could still do an explicit for-loop:

my_dict = {}
for k in my_list:
    my_dict[k] = 0
Ry-
  • 218,210
  • 55
  • 464
  • 476
Ma0
  • 15,057
  • 4
  • 35
  • 65
  • 6
    or even `dict.fromkeys(my_list,0)` – Chris_Rands Mar 10 '17 at 14:37
  • 2
    There are many duplicate of this answer floating around Stack Overflow. If OP actually just google his problem it would link to at least 3.... Maybe try flagging it instead of promoting this behavior. But nevertheless it's an answer – MooingRawr Mar 10 '17 at 14:37
  • 1
    Actually i didn't knew the exact term to search for. :p – codenamered5 Mar 10 '17 at 14:38
  • @Ev.Kounis is the possible to change(i mean increase or decrease) the value associated with each key via a loop or something (after initializing the dictionary)? – codenamered5 Mar 10 '17 at 15:22
  • for a specific key or for all keys? – Ma0 Mar 10 '17 at 15:31
  • @Ev.Kounis what i wanna do is to initialize the values to each key as 0. After that i want to run a `for` loop in a list of numbers. If the same number is found as a value in the dictionary i want to increase it's key every time that number is found. when i try to access the value,the above method produces an error " 'int' object is not iterable" . Long story short: specific key – codenamered5 Mar 10 '17 at 15:39
  • `for item in my_other_list: if item in my_dict: my_dict[item] += 1` – Ma0 Mar 10 '17 at 15:48
1

Another solution:

l =  [2, 3, 5, 7, 11]
d = {}

for item in l:
    d[item] = 0
Ambitions
  • 2,369
  • 3
  • 13
  • 24