manateejoe - 1 year ago 136

Python Question

I have a dictionary created from variables in a netCDF file. I have also sorted all of these variables in the order of time. There are repeated values for some of the keys. I want to find all of the indices for a specific value in one key and retrieve the corresponding indices from another key:

For example:

`test_dict = {}`

test_dict['time'] = [1,2,3,4]

test_dict['number'] = [12,14,12,13]

test_dict['number2'] = [20,21,22,23]

in test_dict I want to find the indices of all occurrences of 12 in the key 'number' and get the corresponding values in 'number2'. So the result should be:

`idx = [0,2]`

nums_interest = [test_dict['number2'][i] for i in idx]

>>>> [20,22]

I have tried to find the number of unique values in 'number' using:

`num_unique = np.unique(test_dict['number'])`

>>>> [12,13,14]

Then I want to find all indices of these unique occurrences.

`idx2 = [test_dict['number'].index(num_unique[0])`

>>> 0

I have two main problems: 1. I can find the first index, but not repeating indices.

2. I want to loop through the list of unique numbers and get indices for every unique value not just num_unique[0]

question: what is the best way to find indices for a certain value in a dictionary and extract the values for the same indices in a different key?

Answer Source

**To return values from one key based on index of another key in a dict**

```
test_dict = {}
test_dict['number'] = [12,14,12,13]
test_dict['number2'] = [20,21,22,23]
print([j for i,j in zip(test_dict['number'],test_dict['number2']) if i==12])
```

returns `[20,22]`

**To get indices of all occurences of a value in a list**

```
indices = [i for i,j in enumerate(dict['number']) if j==12]
```

gives `indices`

equals `[0,2]`