list - Sequence of dictionaries in python -


i trying create sequence of similar dictionaries further store them in tuple. tried 2 approaches, using , not using loop

without loop

dic0 = {'modo': lambda x: x[0]} dic1 = {'modo': lambda x: x[1]} lst = [] lst.append(dic0) lst.append(dic1) tup = tuple(lst) dic0 = tup[0] dic1 = tup[1] f0 = dic0['modo'] f1 = dic1['modo'] x = np.array([0,1]) print (f0(x) , f1(x))  # 0 , 1 

with loop

lst = [] j in range(0,2):     dic = {}     dic = {'modo': lambda x: x[j]}     lst.insert(j,dic) tup = tuple(lst) dic0 = tup[0] dic1 = tup[1] f0 = dic0['modo'] f1 = dic1['modo'] x = np.array([0,1]) print (f0(x) , f1(x))   # 1 , 1 

i don't understand why getting different results. seems last dictionary insert overwrite previous ones, don't know why (the append method not work neither).

any welcomed

this happening due how scoping works in case. try putting j = 0 above final print statement , you'll see happens.

also, might try

from operator import itemgetter  lst = [{'modo': itemgetter(j)} j in range(2)]  

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

python - cx_oracle unable to find Oracle Client -