itjcms18
itjcms18

Reputation: 4343

using a dictionary to cut down a list of tuples

i'm trying to use a dictionary to cut down a list of tuples. the starting point is shown below. i also included a dictionary - the values in the dictionary is what i am trying to use to cut down my list of tuples

start = [('bryan', 'lucy'), ('david', 'lucy')]

dic = {'bryan': 4.9, 'lucy': 7.5, 'david': 8.0}

i want it so any tuple that has elements with a difference greater than 1 (according to the value in the dictionary) to be removed. in this case the desired output would be

[('david','lucy')]

b/c the absolute value of david - lucy = 0.5

here is my (failed) attempt to solve my problem.

end = []

for i in range(0,len(start)):
    if abs(dic[start[i][0]] - dic[start[i][1]]) < 1.0001:
        end.append(dic[start[i]])

any help would be greatly appreciated

Upvotes: 1

Views: 71

Answers (3)

Neel
Neel

Reputation: 21297

Try this

In [13]: [x for x in start if abs(dic[x[0]] - dic[x[1]]) < 1.0001]
Out[13]: [('david', 'lucy')]

This is list comprehension in python. It will check for all attributes in list and compare condition abs(dic[x[0]] - dic[x[1]]) < 1.0001 element who fulfill this condition will return.

Upvotes: 0

Andrew Johnson
Andrew Johnson

Reputation: 3186

A list comprehension can make this a one-liner

[ (l,r) for (l,r) in start if abs(dic[l]-dic[r])<1.0001 ]

Upvotes: 1

BWStearns
BWStearns

Reputation: 2706

A list comprehension can help you out here.

[(e,o) for e, o in start if -1 < dic[e]-dic[o] < 1]

Upvotes: 1

Related Questions