Issue
hi i have python sub dictionary like this
import torch
import torch.nn as nn
dic = {
"A": [0.2822, -0.0958, -0.5165, -0.3812,
-0.3469, 0.4025, -0.0696, -0.1246,
-0.1132, 0.4170, -0.0383, -0.4071,
-0.5407, 0.1519, 0.5630, 0.1276],
"B": [1.0014, 0.9980, 1.0012, 0.9986,
1.0001, 0.9999, 1.0016, 1.0014,
1.0008, 0.9996, 1.0008, 1.0004,
1.0000, 0.9987, 0.9997, 0.9989]
}
for key 1 i have 16 values, i want to make 2 chunks of size 8 for key A. how it can be possible?
Like first 8 values stored in separate array and last 8 values stoed ins eparate array or dictionary with their key values. as shown in this image
Solution
First of all, I'd refer to keys as what they are (i.e. Key 'A' has 16 values, not key 1). It's a good practice to just think of dictionaries as unordered and simply a group of key-value pairs.
Second, using numpy will allow us to split the key we want into two (or more) even groups. If you end up needing to split a list of 30 elements into three lists, this code will still work.
import numpy as np
dic = {
"A": [0.2822, -0.0958, -0.5165, -0.3812,
-0.3469, 0.4025, -0.0696, -0.1246,
-0.1132, 0.4170, -0.0383, -0.4071,
-0.5407, 0.1519, 0.5630, 0.1276],
"B": [1.0014, 0.9980, 1.0012, 0.9986,
1.0001, 0.9999, 1.0016, 1.0014,
1.0008, 0.9996, 1.0008, 1.0004,
1.0000, 0.9987, 0.9997, 0.9989]
}
# We give array_split() our list, and how many we want it split into.
a1, a2 = np.array_split(dic['A'], 2) # We get our two lists returned.
dic['A1'] = a1.tolist() # Numpy returns it as an np.array, so let's put it back into a list.
dic['A2'] = a2.tolist()
del(dic['A']) # Remove the now unused key-value.
{'B': [1.0014, 0.998, 1.0012, 0.9986, 1.0001, 0.9999, 1.0016, 1.0014, 1.0008, 0.9996, 1.0008, 1.0004, 1.0, 0.9987, 0.9997, 0.9989],
'A1': [0.2822, -0.0958, -0.5165, -0.3812, -0.3469, 0.4025, -0.0696, -0.1246],
'A2': [-0.1132, 0.417, -0.0383, -0.4071, -0.5407, 0.1519, 0.563, 0.1276]}
Answered By - FlapJack
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.