Home > Back-end >  Multidimensional dictionary comprehension
Multidimensional dictionary comprehension

Time:02-14

Say I have a dictionary like this:

d = {key1: [1,2,3], key2: [4,6,7]}

If I want to have a dictionary which subtracts from the values the mean of the respective array I can do:

new_d = {key: x - np.mean(x) for (key,x) in d.items()}

Now say my dictionary actually looks like this:

d = {key1: [[1,2,3], [10,100,1000]], key2: [[4,5,6], [11,12,16]]}

How would dictionary comprehension work in this case?

The result should look like this:

new_d = {key1: [[-1, 0, 1], [-360, -270, 630]], key2: [[-1, 0, 1], [-2, -1, 3]]}

Thanks for your help!

CodePudding user response:

Using the same comprehension as yours with one extra level for the sublist:

new_d = {key: [x - np.mean(x) for x in l] for (key,l) in d.items()}

As lists:

{key: [(x - np.mean(x)).tolist() for x in l] for (key,l) in d.items()}

output:

{'key1': [[-1.0, 0.0, 1.0], [-360.0, -270.0, 630.0]],
 'key2': [[-1.0, 0.0, 1.0], [-2.0, -1.0, 3.0]]}

CodePudding user response:

Following from your 1D solution, you just need a nested list comprehension:

>>> {key: [y-np.mean(y) for y in x] for key,x in d.items()}
{'key1': [array([-1.,  0.,  1.]), array([-360., -270.,  630.])],
 'key2': [array([-1.,  0.,  1.]), array([-2., -1.,  3.])]}

But if you want exactly the output you wrote using idiomatic NumPy, it's a bit different:

  1. Specify int datatype
  2. Take the mean across rows
  3. Convert back to list
>>> {key: (x - np.mean(x, axis=1, keepdims=True, dtype='int')).tolist()
...  for key,x in d.items()}
{'key1': [[-1, 0, 1], [-360, -270, 630]],
 'key2': [[-1, 0, 1], [-2, -1, 3]]}
  • Related