Browse, compare and assign dictionaries and lists

3

I have an array called labels such that:

labels
Out[15]: array([ 0,  1,  2, ...,  7, 10, -1])

I also have a dictionary called IDnodes which contains for each key an array of Boolean type and each array is of a different length.

I want to have a dictionary called Temp in which to store for each key (of the same value as in IDnodes) a list like the labels but that fulfills the following, for example:

IDnodes[key1]=array([ True, False, False, ..., False, False,  True], dtype=bool)

If the value of a certain key is True, then I want to save in Temp of that same key the value of labels of that same position.

labels is traversed from the first value and only the position is advanced if the value of IDnodes is True, if False is not advanced.

If the value is False, then I want to save a value of -1 .

And then have in Temp[key1] something like:

Temp[key1]=array([ 5, -1, -1, ..., -1, -1,  8], dtype=int64)

My attempts have been in vain:

i=0
lista=[]
Temp=dict.fromkeys(IDnodes.keys(),[])
for mmsi, val in IDnodes.items():
    for p in val:
        if p:
            lista.append(labels[i])
            i+=1
        else:
            lista.append(-1)
    Temp[mmsi]=lista
    lista=[]
    
asked by Juanca M 08.05.2017 в 11:00
source

1 answer

1

A line of code, look.

i = 0
lista=[]
Temp=dict.fromkeys(IDnodes.keys(),[])
for mmsi, val in IDnodes.items():
    for p in val:
        if p:
            lista.append(labels[mmsi][i]) # <- aquí
            i+=1
        else:
            lista.append(-1)
    Temp[mmsi]=lista
    lista=[]

Alternative 1:

Temp=dict.fromkeys(IDnodes.keys(),[])
for mmsi, val in IDnodes.items():
    lista=[]
    for i, p in enumerate(val):
        if p:
            lista.append(labels[mmsi][i])
        else:
            lista.append(-1)
    Temp[mmsi]=lista

Alternative 2

Temp = {}
for mmsi, val in IDnodes.items():
    Temp[mmsi] = [(labels[mmsi][i] if p else -1) \
                  for i, p in enumerate(val)
                  ]
    
answered by 15.11.2017 в 09:07