pythonordereddict

How to slice value element in orderedDict in python?


SO,I have this code , how to sliced up value elements in orderedDict?

import numpy as np
from collections import OrderedDict
x = OrderedDict()
val= np.array((1,2))
key= 40
x[key]= val
x[key]= val,3
print(x)

returns :

OrderedDict([(40, (array([1, 2]), 3))]) #  <- i want to slice this 2nd value element 

target output:

OrderedDict([(40, array([1, 2])])  

Solution

  • @Caina is close, but his version is not quite right in that it leaves an extra collection layer in the result. This is the expression that returns the exact result you requested:

    x_sliced = OrderedDict({k:x[k][0] for k in x})
    

    Result:

    OrderedDict([(40, array([1, 2]))])
    

    Actually, this isn't technically what you asked for. Your version has one missing closing ')', but that's just a typo I assume.