0

I have two lists like these:

a = [12, 23, 45, 56]
b = [0, 0, 0, 0]

And I want to create a dict using a and b like this:

c = {12:0, 23:0, 45:0, 56:0}

Is there a easy method to do this?

Just_Me
  • 111
  • 8

2 Answers2

1

Yes, using dict and zip.

a = [12, 23, 45, 56]
b = [0, 0, 0, 0]
c = dict(zip(a,b))

zip iterates through your lists in parallel, delivering them in pairs. dict accepts a sequence of key/value pairs and uses them to make a dictionary.

If you actually want a dictionary where every value is zero, you don't even need the b list. You can just have

c = {k:0 for k in a}
khelwood
  • 55,782
  • 14
  • 81
  • 108
-1

Just loop through them together:

c = {}
for i,j in zip(a,b):
    c[i] = j

Or either a direct usage of zip and dict together:

keys = ()
values = ()
result = dict(zip(keys, values))
# or
result = {k: v for k, v in zip(keys, values)}
Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34
  • 1
    I think dict(zip(a,b)) is easier – Just_Me May 13 '20 at 19:21
  • yep it is :) a simpler solution for beginners :) – Joshua Varghese May 13 '20 at 19:22
  • I am sorry, but I am using python for 4 years :D – Just_Me May 13 '20 at 19:23
  • 2
    I didn't downvote, but a lot of these really shouldn't be recommened aside from `dict(zip(keys, values))`. The loop, and dictionary comprehension for example. Everytime you see something like `result = {k: v for k, v in whatever}` it should be `dict(whatever)`, similarly with list comprehensions, `[x for x in whatever]` should just be `list(whatever)`. Some people will downvote answers / questions that they consider "obvious" duplicates. I think that's harsh but some people do it. – juanpa.arrivillaga May 13 '20 at 19:34