PyRsquared
PyRsquared

Reputation: 7338

Using zip and list comprehension to create a dictionary

I have two arrays:

a = [0.001,0.01,0.1,1]
h = [2,4,8,16,32,64]

And I want to create a dictionary, where the dict keys are a tuple of the values of a and h and the dict values are an empty list. However, the way I need this done is so that each unique a has every value in h, with the desired output:

 d = {(0.001,2):[], (0.001,4):[], (0.001,8):[], (0.001,16):[], (0.001,32):[], (0.001,64):[],
   (0.01,2):[], (0.01,4):[], (0.01,8):[], (0.01,16):[], (0.01,32):[], (0.01,64):[],
   (0.1,2):[], (0.1,4):[], (0.1,8):[], (0.1,16):[], (0.1,32):[], (0.1,64):[],
   (1,2):[], (1,4):[], (1,8):[], (1,16):[], (1,32):[], (1,64):[]}

The problem is, writing it out manually as I have done above is tedious.

Is there anyway to do this, using zip or list comprehension? Thanks in advance

Upvotes: 2

Views: 764

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

what you need is not zip which doesn't combine your lists but rather itertools.product in a dict comprehension:

import itertools

a = [0.001,0.01,0.1,1]
h = [2,4,8,16,32,64]

d = {z:[] for z in itertools.product(a,h)}

print(d)

result:

{(0.01, 2): [], (0.1, 64): [], (0.001, 64): [], (0.01, 64): [], (0.001, 2): [], (1, 4): [], (0.01, 4): [], (1, 64): [], (0.1, 8): [],
(0.01, 8): [], (1, 2): [], (0.1, 32): [], (0.001, 32): [], (0.01, 32): [], (1, 16): [], (0.001, 8): [], (1, 8): [], (0.1, 16): [],
(0.001, 16): [], (0.01, 16): [], (0.001, 4): [], (1, 32): [], (0.1, 4): [], (0.1, 2): []}

Upvotes: 7

Related Questions