简体   繁体   中英

Extracting dictionary values in for loop to fill list

I have this code:

import numpy as np

result = {}
result['depth'] = [1,1,1,2,2,2]
result['generation'] = [1,1,1,2,2,2]
result['dimension'] = [1,2,3,1,2,3]
result['data'] = [np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0])]

for v in np.unique(result['depth']):
    temp_v = np.where(result['depth'] ==  v)
    values_v = [result[string][temp_v] for string in result.keys()]
    this_v = dict(zip(result.keys(), values_v))

in which I want to create a new dict called ' this_v ', with the same keys as the original dict result , but fewer values.

The line:

values_v = [result[string][temp_v] for string in result.keys()]

gives an error

TypeError: list indices must be integers, not tuple

which I don't understand, since I can create ex = result[result.keys()[0]][temp_v] just fine. It just does not let me do this with a for loop so that I can fill the list.

Any idea as to why it does not work?

I'm not sure what you are trying to achieve but I could solve your issue:

np.where is returning a tuple, so to access you need to do give the index temp_v[0]. Also the value of the tuple is an array so to loop over the value you need to run another loop a for a in temp_v[0] which helps you you access the value.

import numpy as np

result = {}
result['depth'] = [1,1,1,2,2,2]
result['generation'] = [1,1,1,2,2,2]
result['dimension'] = [1,2,3,1,2,3]
result['data'] = [np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0])]

for v in np.unique(result['depth']):
    temp_v = np.where(result['depth'] ==  v)
    values_v = [result[string][a] for a in temp_v[0] for string in result.keys()]
    this_v = dict(zip(result.keys(), values_v))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM