Arun Arun - 2 months ago 7
Python Question

Manipulating list of lists and dictionary

I have a list of lists representing the keys in a dictionary. I wish to pickup the smaller key for each list in lists. For instance,

L1 = [['1_A','2_A'],['1_B','2_B']]
D1 = {'1_A': 0.22876, '2_A': 0.22382, '1_B': 0.2584, '2_B': 0.25373}

for li in L1:
for ll in li:
if ll in D1.keys():
print "Value for %s is %s" %(ll,D1[ll])
else:
print "Values not found"


When I print it, I get:

Value for 1_A is 0.22876
Value for 2_A is 0.22382
Value for 1_B is 0.2584
Value for 2_B is 0.25373


The output I expect is
2_A
,
2_B
since both of them have smaller values compared to
1_A
and
1_B
respectively. Can anyone suggest how to do this?

Answer

You're not comparing the values anywhere.

L1 = [['1_A','2_A'],['1_B','2_B']]
D1 = {'1_A': 0.22876, '2_A': 0.22382, '1_B': 0.2584, '2_B': 0.25373}

template = "Value for {} is {}"

for i,j in L1:
    if D1[i] < D1[j]:
        print template.format(i,D1[i])
    else:
        print template.format(j,D1[j])